forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShellSorter.cs
55 lines (52 loc) · 1.74 KB
/
ShellSorter.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
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison
{
/// <summary>
/// TODO.
/// </summary>
/// <typeparam name="T">TODO. 2.</typeparam>
public class ShellSorter<T> : IComparisonSorter<T>
{
/// <summary>
/// Sorts array using specified comparer,
/// based on bubble sort,
/// internal, in-place, unstable,
/// worst-case time complexity: O(n^2),
/// space complexity: O(1),
/// where n - array length.
/// </summary>
/// <param name="array">Array to sort.</param>
/// <param name="comparer">Compares elements.</param>
public void Sort(T[] array, IComparer<T> comparer)
{
for (var step = array.Length / 2; step > 0; step /= 2)
{
for (var i = 0; i < step; i++)
{
GappedBubbleSort(array, comparer, i, step);
}
}
}
private static void GappedBubbleSort(T[] array, IComparer<T> comparer, int start, int step)
{
for (var j = start; j < array.Length - step; j += step)
{
var wasChanged = false;
for (var k = start; k < array.Length - j - step; k += step)
{
if (comparer.Compare(array[k], array[k + step]) > 0)
{
var temp = array[k];
array[k] = array[k + step];
array[k + step] = temp;
wasChanged = true;
}
}
if (!wasChanged)
{
break;
}
}
}
}
}