-
Notifications
You must be signed in to change notification settings - Fork 1
/
104-heap_sort.c
73 lines (62 loc) · 1.35 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
73
#include "sort.h"
/**
* heap_sort - Function that sorts ints w/ heap sort algorithm
* @array: The array of integers
* @size: The array size
*
* Return: None
*/
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(array, array + i);
print_array(array, size);
heapify(array, size, i, 0);
}
}
/**
* heapify - A function that heapifies a binary tree
* @array: The array of integers in a binary tree
* @size: The array size
* @base: The index of the base row of the binary tree
* @root: The root node of the binary tree
*
* Return: None
*/
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(array + root, array + large);
print_array(array, size);
heapify(array, size, base, large);
}
}
/**
* swap - Function to swap position of 2 elements in list
* @first: Fist element
* @second: Second element
*
* Return: None
*/
void swap(int *first, int *second)
{
int tmp_elem;
tmp_elem = *first;
*first = *second;
*second = tmp_elem;
}