Skip to content

Commit 4875c62

Browse files
authored
Merge pull request AllAlgorithms#208 from Shradha27/shell-sort
Add shell sort algorithm
2 parents 87ec985 + b1c7da1 commit 4875c62

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

sorting/shell_sort.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//
2+
// C++ implementation of shell sort
3+
//
4+
// The All ▲lgorithms Project
5+
//
6+
// https://allalgorithms.com/sorting
7+
// https://github.com/allalgorithms/cpp
8+
//
9+
// Contributed by: Shradha Sharma
10+
// Github: @shradha27
11+
//
12+
#include<iostream>
13+
14+
using namespace std;
15+
16+
// A function implementing Shell sort.
17+
void ShellSort(int a[], int n)
18+
{
19+
int i, j, k, temp;
20+
// Gap 'i' between index of the element to be compared, initially n/2.
21+
for(i = n/2; i > 0; i = i/2)
22+
{
23+
for(j = i; j < n; j++)
24+
{
25+
for(k = j-i; k >= 0; k = k-i)
26+
{
27+
// If value at higher index is greater, then break the loop.
28+
if(a[k+i] >= a[k])
29+
break;
30+
// Switch the values otherwise.
31+
else
32+
{
33+
temp = a[k];
34+
a[k] = a[k+i];
35+
a[k+i] = temp;
36+
}
37+
}
38+
}
39+
}
40+
}
41+
int main()
42+
{
43+
int n, i;
44+
cout<<"\nEnter the number of data element to be sorted: ";
45+
cin>>n;
46+
47+
int arr[n];
48+
for(i = 0; i < n; i++)
49+
{
50+
cout<<"Enter element "<<i+1<<": ";
51+
cin>>arr[i];
52+
}
53+
54+
ShellSort(arr, n);
55+
56+
// Printing the sorted data.
57+
cout<<"\nSorted Data ";
58+
for (i = 0; i < n; i++)
59+
cout<<"->"<<arr[i];
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)