forked from dayoonasanya/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104-heap_sort.c
72 lines (56 loc) · 1 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
66
67
68
69
70
71
72
#include "sort.h"
/**
* heapify - heap.
* @array: array.
* @size: size.
* @base: base.
* @root: base.
*/
void heapify(int *array, size_t size, size_t base, size_t root)
{
size_t left, right, large;
left = 2 * root + 1;
right = 2 * root + 2;
large = root;
if (left < base && array[left] > array[large])
large = left;
if (right < base && array[right] > array[large])
large = right;
if (large != root)
{
swap_func(array + root, array + large);
print_array(array, size);
heapify(array, size, base, large);
}
}
/**
* heap_sort -sort.
* @array: array.
* @size: size
*/
void heap_sort(int *array, size_t size)
{
int i;
if (array == NULL || size < 2)
return;
for (i = (size / 2) - 1; i >= 0; i--)
heapify(array, size, size, i);
for (i = size - 1; i > 0; i--)
{
swap_func(array, array + i);
print_array(array, size);
heapify(array, size, i, 0);
}
}
/**
* swap_func - swap
* @a: a
* @b: b
*/
void swap_func(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}