cocktail sort Algorithm

Cocktail sort, also known as bidirectional bubble sort, shaker sort, ripple sort, or cocktail shaker sort, is an efficient optimization of the original bubble sort algorithm. It functions by sorting the list of elements, comparing adjacent items, and swapping them if they are in the wrong order. The primary distinction from the traditional bubble sort is that the cocktail sort algorithm sorts the list in both directions, from left to right and then from right to left. This bidirectional approach eliminates the need for multiple passes over the entire list and reduces the number of comparisons required, resulting in a faster sorting process. In the first pass of the cocktail sort algorithm, the smallest element is bubbled to the beginning of the list, while the largest element is bubbled to the end of the list simultaneously. This process is repeated on the subsequent passes, narrowing the range of the unsorted elements with each iteration. As the sorting continues, the range of unsorted elements gradually shrinks, and the algorithm stops when there are no more swaps needed, indicating that the list is now sorted. The cocktail sort algorithm is best suited for lists that are already partially sorted, as it can handle such cases more efficiently than the original bubble sort. However, it still possesses an average-case and worst-case time complexity of O(n^2), making it inefficient for large datasets compared to more advanced sorting algorithms like quicksort or merge sort.
package main

/*
 * Cocktail sort - https://en.wikipedia.org/wiki/Cocktail_sort
 */

func CocktailSort(arr []int) {
	tmp := 0

	for i := 0; i < len(arr)/2; i++ {
		left := 0
		right := len(arr) - 1

		for left <= right {

			if arr[left] > arr[left+1] {
				tmp = arr[left]
				arr[left] = arr[left+1]
				arr[left+1] = tmp
			}

			left++

			if arr[right-1] > arr[right] {
				tmp = arr[right-1]
				arr[right-1] = arr[right]
				arr[right] = tmp
			}

			right--
		}
	}
}

LANGUAGE:

DARK MODE: