forked from Obelem/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path100-shell_sort.c
63 lines (58 loc) · 997 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "sort.h"
/**
* _swap - swap two numbers.
* @a: integer
* @b: integer
**/
void _swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* backward_insertion -swap two nodes right left position
* @array: array
* @gap: gap
* @act: actual position in the array
**/
void backward_insertion(int *array, int gap, int act)
{
int i;
for (i = act - gap; i >= 0; i -= gap, act -= gap)
{
if (array[i] > array[act])
_swap(&array[i], &array[act]);
else
break;
}
}
/**
* shell_sort -Sort an array using shell_sort algorithm
* @array: array
* @size: size
**/
void shell_sort(int *array, size_t size)
{
unsigned int gap = 1, i, j;
if (array == NULL)
return;
if (size < 2)
return;
while (gap < size / 3)
gap = gap * 3 + 1;
while (gap > 0)
{
for (i = 0, j = gap; j < size; i++, j++)
{
if (array[i] > array[j])
{
_swap(&array[i], &array[j]);
backward_insertion(array, gap, i);
}
}
print_array(array, size);
gap /= 3;
}
}