Cocktail Sorter Algorithm

The Cocktail Sorter Algorithm, also known as Shaker Sort or Bidirectional Bubble Sort, is a variation of the Bubble Sort algorithm that sorts a list of elements by comparing and swapping adjacent pairs in a bidirectional manner. In simple terms, it works by sorting the list in both forward and reverse directions, similar to how a cocktail shaker mixes drinks by shaking them back and forth. This approach helps in moving small and large elements to their correct positions more efficiently than the traditional Bubble Sort algorithm. The algorithm begins by iterating through the list from the beginning to the end, comparing adjacent elements and swapping them if they are in the wrong order. This phase is similar to the Bubble Sort, where the largest element in the unsorted section of the list "bubbles up" to its correct position at the end of the list. The Cocktail Sort then reverses direction and iterates from the end of the list back to the beginning, again comparing adjacent elements and swapping them if necessary. This reverse pass ensures that the smallest element in the unsorted section "bubbles down" to its correct position at the beginning of the list. This bidirectional process continues until the entire list is sorted, making the Cocktail Sort more efficient than the traditional Bubble Sort, particularly for lists with a small number of misplaced elements.
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison
{
/// <summary>
/// Cocktail Sort is a variation of Bubble sort, where Cocktail
/// Sort traverses through a given array in both directions alternatively.
/// </summary>
/// <typeparam name="T">Array input type.</typeparam>
public class CocktailSorter<T> : IComparisonSorter<T>
{
/// <summary>
/// Sorts array using Cocktail sort algorithm.
/// </summary>
/// <param name="array">Input array.</param>
/// <param name="comparer">Type of comparer for array elements.</param>
public void Sort(T[] array, IComparer<T> comparer) => CocktailSort(array, comparer);
private static void CocktailSort(IList<T> array, IComparer<T> comparer)
{
var swapped = true;
var startIndex = 0;
var endIndex = array.Count - 1;
while (swapped)
{
for (var i = startIndex; i < endIndex; i++)
{
if (comparer.Compare(array[i], array[i + 1]) != 1)
{
continue;
}
var highValue = array[i];
array[i] = array[i + 1];
array[i + 1] = highValue;
}
endIndex--;
swapped = false;
for (var i = endIndex; i > startIndex; i--)
{
if (comparer.Compare(array[i], array[i - 1]) != -1)
{
continue;
}
var highValue = array[i];
array[i] = array[i - 1];
array[i - 1] = highValue;
swapped = true;
}
startIndex++;
}
}
}
}

LANGUAGE:

DARK MODE: