public static void CocktailSort(SortingArray array) { int left = 0; int right = array.Length - 1; while (left < right) { for (int i = left; i < right; i++) { if (array.IsBigger(i, i + 1)) { array.Swap(i, i + 1); } Updated(array); } for (int i = right; i > left; i--) { if (array.IsSmaller(i, i - 1)) { array.Swap(i, i - 1); } Updated(array); } left++; right--; } }
public static void OptimizedCocktailSort(SortingArray array) { int left = 0; int right = array.Length - 1; while (left < right) { int nextLeft = right; int nextRight = left; bool sorted = true; for (int i = left; i < right; i++) { if (array.IsBigger(i, i + 1)) { array.Swap(i, i + 1); sorted = false; nextRight = i; } Updated(array); } if (sorted) { break; } right = nextRight; for (int i = right; i > left; i--) { if (array.IsSmaller(i, i - 1)) { array.Swap(i, i - 1); sorted = false; nextLeft = i; } Updated(array); } if (sorted) { break; } left = nextLeft; } }