-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellSort.cpp
More file actions
56 lines (45 loc) · 872 Bytes
/
ShellSort.cpp
File metadata and controls
56 lines (45 loc) · 872 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Shell Sort
//move more than one position at a time by h-sorting the array.
//time: O(n^2) compares, O(n^2) exchanges
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define SORT_NUM 20
void swap(int *a,int m,int n)
{
int tmp = a[m];
a[m] = a[n];
a[n] = tmp;
}
void display(int *a,int num)
{
for(int i=0;i<num;i++)
cout << "sorted array [" << i << "] = " << a[i] << endl;
}
void ShellSort(int *a,int num)
{
int h = 1;
while(h<num/3)
h = h*3+1;
while(h>=1)
{
for(int i=h;i<num;i++)
{
for(int j=i;j>=h && a[j]<a[j-h];j-=h)
swap(a,j,j-h);
}
h/=3;
}
}
int main()
{
int num = SORT_NUM;
int a[num]= {0};
srand((int)time(0));
for(int i=0;i<num;i++)
a[i] = rand()%100;
ShellSort(a,num);
display(a,num);
return 0;
}