Skip to content

Commit 35a0185

Browse files
authored
Merge pull request Astrodevil#367 from arihantj13/arihant
Added Shell Sort
2 parents 2851c16 + 89109a3 commit 35a0185

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// C++ implementation of Shell Sort
2+
#include <iostream>
3+
using namespace std;
4+
5+
// Function to sort array using shellSort
6+
int shellSort(int arr[], int n)
7+
{
8+
// Start with a big gap, then reduce the gap
9+
for (int gap = n/2; gap > 0; gap /= 2)
10+
{
11+
/* Do a gapped insertion sort for this gap size.
12+
The first gap elements a[0..gap-1] are already in gapped order
13+
keep adding one more element until the entire array is
14+
gap sorted */
15+
for (int i = gap; i < n; i += 1)
16+
{
17+
/*add a[i] to the elements that have been gap sorted
18+
save a[i] in temp and make a hole at position i */
19+
int temp = arr[i];
20+
21+
/*shift earlier gap-sorted elements up until the correct
22+
location for a[i] is found*/
23+
int j;
24+
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
25+
arr[j] = arr[j - gap];
26+
27+
// put temp (the original a[i]) in its correct location
28+
arr[j] = temp;
29+
}
30+
}
31+
return 0;
32+
}
33+
34+
void printArray(int arr[], int n)
35+
{
36+
for (int i=0; i<n; i++)
37+
cout << arr[i] << " ";
38+
cout<<endl;
39+
}
40+
41+
int main()
42+
{
43+
int n;
44+
cout<<"Enter number of elements in array\n";
45+
cin>>n;
46+
47+
int arr[n], i;
48+
cout<<"Enter elements of array\n";
49+
for(i=0;i<n;i++)
50+
{
51+
cin>>arr[i];
52+
}
53+
54+
cout << "Array before sorting: \n";
55+
printArray(arr, n);
56+
57+
shellSort(arr, n);
58+
59+
cout << "Array after sorting: \n";
60+
printArray(arr, n);
61+
62+
return 0;
63+
}

0 commit comments

Comments
 (0)