forked from Obelem/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path104-heap_sort.c
65 lines (59 loc) · 1.19 KB
/
104-heap_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
#include "sort.h"
/**
* swap_root - A function that swap the root nodes.
* @array: The heap to sort.
* @root: The root of the heap.
* @hi: The higher index.
* @size: The size of the array.
* Return: Nothing
*/
void swap_root(int *array, size_t root, size_t hi, size_t size)
{
size_t lo = 0, mi = 0, tmp = 0;
int aux = 0;
while ((lo = (2 * root + 1)) <= hi)
{
tmp = root;
mi = lo + 1;
if (array[tmp] < array[lo])
tmp = lo;
if (mi <= hi && array[tmp] < array[mi])
tmp = mi;
if (tmp == root)
return;
aux = array[root];
array[root] = array[tmp];
array[tmp] = aux;
print_array(array, size);
root = tmp;
}
}
/**
* heap_sort - A function that sorts an array using heap algorithm.
* @array: An array to sort.
* @size: The size of the array.
* Return: Nothing.
*/
void heap_sort(int *array, size_t size)
{
size_t hi = 0, gap = 0;
int tmp = 0;
if (array == NULL || size < 2)
return;
for (gap = (size - 2) / 2; 1; gap--)
{
swap_root(array, gap, size - 1, size);
if (gap == 0)
break;
}
hi = size - 1;
while (hi > 0)
{
tmp = array[hi];
array[hi] = array[0];
array[0] = tmp;
print_array(array, size);
hi--;
swap_root(array, 0, hi, size);
}
}