Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 17376ae

Browse files
Merge pull request fnplus#582 from iamvkundra/master
Create shellsort.cpp
2 parents 355010b + 148dfb2 commit 17376ae

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2+
#include <iostream>
3+
using namespace std;
4+
5+
/* function to sort arr 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+
}
39+
40+
int main()
41+
{
42+
int arr[] = {12, 34, 54, 2, 3}, i;
43+
int n = sizeof(arr)/sizeof(arr[0]);
44+
45+
cout << "Array before sorting: \n";
46+
printArray(arr, n);
47+
48+
shellSort(arr, n);
49+
50+
cout << "\nArray after sorting: \n";
51+
printArray(arr, n);
52+
53+
return 0;
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /