-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-shell_sort.c
47 lines (39 loc) · 983 Bytes
/
100-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
#include "sort.h"
void shell_sort(int *array, size_t size);
void swap_shell(int *array, int item1, int item2);
/**
* shell_sort - sorts an array of integers in ascending
* order using the Shell sort algorithm, using the Knuth sequence
* @size: size of the array
* @array: numbered list
*/
void shell_sort(int *array, size_t size)
{
size_t gap = 1, i, index = 0;
if (array == NULL || size < 2)
return;
while (gap < size / 3)
gap = 3 * gap + 1;
while (gap >= 1)
{
for (i = gap; i < size; i++)
for (index = i; index >= gap &&
(array[index] < array[index - gap]); index -= gap)
swap_shell(array, index, index - gap);
print_array(array, size);
gap /= 3;
}
}
/**
*swap_shell - changes the positions of two elements of an array
*@array: the array to perform swao
*@item1: 1st element
*@item2: 2nd element
*/
void swap_shell(int *array, int item1, int item2)
{
int tmp;
tmp = array[item1];
array[item1] = array[item2];
array[item2] = tmp;
}