Skip to content

Commit 9cd6e76

Browse files
authored
Create ShellSort.cpp
1 parent 6867b39 commit 9cd6e76

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

C++/ShellSort.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
```
2+
/*
3+
Name: Sreejan Chaudhury
4+
College: University of Calcutta
5+
*/
6+
7+
/*
8+
ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead,
9+
many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h.
10+
We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.
11+
*/
12+
13+
// C++ implementation of Shell Sort
14+
#include <iostream>
15+
using namespace std;
16+
17+
/* function to sort arr using shellSort */
18+
int shellSort(int arr[], int n)
19+
{
20+
// Start with a big gap, then reduce the gap
21+
for (int gap = n/2; gap > 0; gap /= 2)
22+
{
23+
// Do a gapped insertion sort for this gap size.
24+
// The first gap elements a[0..gap-1] are already in gapped order
25+
// keep adding one more element until the entire array is
26+
// gap sorted
27+
for (int i = gap; i < n; i += 1)
28+
{
29+
// add a[i] to the elements that have been gap sorted
30+
// save a[i] in temp and make a hole at position i
31+
int temp = arr[i];
32+
33+
// shift earlier gap-sorted elements up until the correct
34+
// location for a[i] is found
35+
int j;
36+
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
37+
arr[j] = arr[j - gap];
38+
39+
// put temp (the original a[i]) in its correct location
40+
arr[j] = temp;
41+
}
42+
}
43+
return 0;
44+
}
45+
46+
void printArray(int arr[], int n)
47+
{
48+
for (int i=0; i<n; i++)
49+
cout << arr[i] << " ";
50+
}
51+
52+
int main()
53+
{
54+
int arr[] = {12, 34, 54, 2, 3}, i;
55+
int n = sizeof(arr)/sizeof(arr[0]);
56+
57+
cout << "Array before sorting: \n";
58+
printArray(arr, n);
59+
60+
shellSort(arr, n);
61+
62+
cout << "\nArray after sorting: \n";
63+
printArray(arr, n);
64+
65+
return 0;
66+
}
67+
68+
/*
69+
Output:
70+
71+
Array before sorting:
72+
12 34 54 2 3
73+
Array after sorting:
74+
2 3 12 34 54
75+
*/
76+
```

0 commit comments

Comments
 (0)