Table of Contents
Introduction
Cocktail sort is the extend version of bubble sort algorithm. The elements are bubbled from both the side alternatively.
Program
def sort(array, length): is_swapped = True first = 0 last = length - 1 while (is_swapped == True): is_swapped = False for i in range(first, last): if (array[i] > array[i+1]): array[i], array[i+1] = array[i+1], array[i] is_swapped = True if(is_swapped == False): last = last-1 for i in range(last-1, first-1, -1): if(array[i] > array[i+1]): array[i], array[i+1] = array[i+1], array[i] is_swapped = True first = first+1 ip_arr = [54, 26, 81, 1] sort(ip_arr, len(ip_arr)) print("The sorted array is ") for i in range(0, len(ip_arr)): print(ip_arr[i])
Output
Explanation
The steps followed in the above code are:
- In first iteration, the element from the left side is compared to each adjacent elements and swapped if required.
- In second iteration, the element from right side just before the recently swapped element is taken and compared to each element to its right and swapped if required.
- In the end the array is sorted and returned.
0 Comments