-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathShellSort.cs
45 lines (35 loc) · 1006 Bytes
/
ShellSort.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
using System;
using System.Collections.Generic;
namespace Advanced.Algorithms.Sorting;
/// <summary>
/// A shell sort implementation.
/// </summary>
public class ShellSort<T> where T : IComparable
{
public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
{
var comparer = new CustomComparer<T>(sortDirection, Comparer<T>.Default);
var k = array.Length / 2;
var j = 0;
while (k >= 1)
{
for (var i = k; i < array.Length; i = i + k, j = j + k)
{
if (comparer.Compare(array[i], array[j]) >= 0) continue;
Swap(array, i, j);
if (i <= k) continue;
i -= k * 2;
j -= k * 2;
}
j = 0;
k /= 2;
}
return array;
}
private static void Swap(T[] array, int i, int j)
{
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}