forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CocktailSorter.cs
61 lines (51 loc) · 1.85 KB
/
CocktailSorter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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++;
}
}
}
}