-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104-heap_sort.c
67 lines (62 loc) · 1.27 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
#include "sort.h"
/**
* swap - swap two elements of the array
* @array: array to swap its elements
* @x: first element
* @y: second element
* Return: Nothing
*/
void swap(int *array, int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
/**
* heapify - compare child nodes with parent node in the max heap
* @array: original array
* @n: part of the heap with nodes to compare
* @i: parent node
* @size: size of the original array
* Return: Nothing
*/
void heapify(int *array, int n, int i, size_t size)
{
int larg = i;
int lft = 2 * i + 1;
int rgt = 2 * i + 2;
if (lft < n && array[lft] > array[larg])
larg = lft;
if (rgt < n && array[rgt] > array[larg])
larg = rgt;
if (larg != i)
{
swap(array, i, larg);
print_array(array, size);
heapify(array, n, larg, size);
}
}
/**
* heap_sort - sort an array in ascending order using the Heap sort algorithm
* @array: array to be sorted
* @size: size of the array
* Return: Nothing
*/
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, i, size);
}
for (i = size - 1; i >= 0; i--)
{
swap(array, 0, i);
if (i != 0)
print_array(array, size);
heapify(array, i, 0, size);
}
}