-
Notifications
You must be signed in to change notification settings - Fork 5
/
shell_sort.c
70 lines (56 loc) · 1.19 KB
/
shell_sort.c
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
/**
* Insertion sort algorithm.
*
* @param int input Array to sort
* @param int n Number of data in search array
*
* @return void
*/
void insertion_sort(int *input, int n, int span)
{
int gap, key;
for (int i = span; i < n; i += span) {
key = input[i];
gap = i - span;
while (gap >= 0 && input[gap] > key) {
input[gap + span] = input[gap];
gap -= span;
}
input[gap + span] = key;
}
}
/**
* Shell sort algorithm.
*
* @param int input Array to sort
* @param int n Number of data in search array
*
* @return void
*/
void shell_sort(int *input, int n)
{
int span = n / 2;
while (span > 0) {
//perform insertion sort on subset
insertion_sort(input, n, span);
span = span / 2;
}
}
int main()
{
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", input + i);
}
shell_sort(input, n);
for (int i = 0; i < n; i++) {
printf("%d\t", *(input + i));
}
free(input);
}