You are on page 1of 2

Shell sort program in C#

In this article, we will write the Shell sort program in C#


Donald Shell published the first version of this sort, hence this is known as Shell sort.
This sorting is a generalization of insertion sort that allows the exchange of items that are
far apart
It starts by comparing elements that are far apart and gradually reduces the gap between
elements being compared.
The running time of Shell sort varies depending on the gap sequence it uses to sort the
elements.

1 private void SortArrayWithShellSort()


2
{
3
int[] array = { 297,183, 464 };
4
ShellSort(array);
5
}
6
7
8
private void ShellSort(int[] array)
9
{
1
int n = array.Length;
0
int gap = n / 2;
1
int temp;
1
1
while (gap > 0)
2
{
1
for (int i = 0; i + gap < n; i++)
3
{
1
int j = i + gap;
4
temp = array[j];
1
5
while (j - gap >= 0 && temp < array[j - gap])
1
{
6
array[j] = array[j - gap];
1
j = j - gap;
7
}
1
8
array[j] = temp;
1
}
9

2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2

gap = gap / 2;
}
}

Output:
183 297 464
2016, admin. All rights reserved.

You might also like