-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCocktailSort.cs
38 lines (34 loc) · 1006 Bytes
/
CocktailSort.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
public class CocktailSort<T> : IGenericSortingAlgorithm<T> where T : IComparable
{
public void Sort(IList<T> list)
{
int start = -1;
int end = list.Count - 2;
bool swapped;
do {
swapped = false;
for (int i = ++start; i <= end; i++) {
if (list[i].CompareTo(list[i + 1]) > 0) {
Swap(list, i, i + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
swapped = false;
for (int i = --end; i >= start; i--) {
if (list[i].CompareTo(list[i + 1]) > 0) {
Swap(list, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
private void Swap(IList<T> list, int a, int b)
{
T temp = list[a];
list[a] = list[b];
list[b] = temp;
}
}