-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-shell_sort.c
More file actions
51 lines (45 loc) · 832 Bytes
/
100-shell_sort.c
File metadata and controls
51 lines (45 loc) · 832 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
#include "sort.h"
/**
* swap - Swap array elements.
*
* @array: The array to be manipulated.
* @idx1: The first index.
* @idx2: The second index.
*/
void swap(int *array, int idx1, int idx2)
{
array[idx2] ^= array[idx1];
array[idx1] ^= array[idx2];
array[idx2] ^= array[idx1];
}
/**
* shell_sort - Shell sort an array using the Knuth sequence.
*
* @array: Array to sort.
* @size: Size of the array.
*/
void shell_sort(int *array, size_t size)
{
size_t gap = 1, i;
int j, k;
if (!array || size <= 1)
return;
while (gap <= size / 3)
gap = gap * 3 + 1;
while (gap > 0)
{
for (i = gap; i < size; i++)
{
k = array[i];
j = i - gap;
while (j >= 0 && k < array[j])
{
array[j + gap] = array[j];
j -= gap;
}
array[j + gap] = k;
}
print_array(array, size);
gap = gap / 3;
}
}