-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellSort.cs
More file actions
92 lines (79 loc) · 2.27 KB
/
ShellSort.cs
File metadata and controls
92 lines (79 loc) · 2.27 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
namespace CSharpSample
{
class Program
{
static void Main(string[] args)
{
ExampleShellSort();
//TestSorting();
}
private static void ShellSort(int[] A, int l, int r)
{
int n = r - l;
int gap = 1;
// 3x + 1 increment sequence is used here
while (gap < n / 3) gap = 3 * gap + 1;
while (gap >= 1)
{
// h-sort the array
for (int i = gap; i < n; i++)
{
for (int j = i; j >= gap && A[j] < A[j - gap]; j -= gap)
{
Swap(ref A[j], ref A[j - gap]);
}
}
gap /= 3;
}
}
private static void ExampleShellSort()
{
const int N = 100;
Random rnd = new Random();
int[] A = new int[N];
for (int i = 0; i < A.Length; i++)
A[i] = rnd.Next(1, N);
foreach (var item in A)
Console.Write(item + " ");
ShellSort(A, 0, A.Length);
Console.WriteLine("\nSorted:");
foreach (var item in A)
Console.Write(item + " ");
Console.WriteLine();
}
private static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
private static bool IsSorted(int[] A)
{
for (int i = 1; i < A.Length; i++)
{
if (A[i] < A[i - 1])
return false;
}
return true;
}
private static void TestSorting()
{
for (int t = 0; t < 100; t++)
{
const int N = 100;
Random rnd = new Random();
int[] A = new int[N];
for (int i = 0; i < A.Length; i++)
A[i] = rnd.Next(1, N);
ShellSort(A, 0, A.Length);
if (!IsSorted(A))
{
foreach (var item in A)
Console.Write(item + " ");
Console.WriteLine();
}
}
}
}
}