Overview
Cocktail Shaker Sort is a variation of Bubble Sort that sorts in
both directions during each pass through the list. It alternates
between left-to-right and right-to-left passes, which helps to move
both small and large elements into their correct positions more
quickly. This bidirectional approach can reduce the number of passes
needed in some cases.
Time Complexity:
Best case: O(n) - When the array is already sorted
Average case: O(n²) - When the array elements are in random order
Worst case: O(n²) - When the array is in reverse order
Space Complexity: O(1) - It is an in-place sorting algorithm.
while (swapped) swapped = false for x = 0 to length(list) - 2 if list[x] > list[x +1] swap(list[x],list[x + 1]) swapped =true if(swapped ==false) break swapped = false for x = length(list) - 2 to 0 if list[x] > list[x +1] swap(list[x],list[x + 1]) swapped =true
SHORT EXPLANATION------------------1. Starting at index 0, compare the current element with the next element - If the current element is greater than the next element, swap them - If the current element is less than the next element, move to the next element2. Repeat Step 1 until you reach the last index3. If no swaps were made, the list is sorted; otherwise, continue4. Starting at index length(list) - 2, compare the current element with the previous element - If the current element is greater than the next element, swap them - If the current element is less than the next element, move to the previous element5. Repeat Step 4 until you reach the first index6. Repeat from Step 1 until no swaps are needed in either direction