-
Notifications
You must be signed in to change notification settings - Fork 0
/
104-heap_sort.c
74 lines (63 loc) · 1.61 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
74
#include "sort.h"
void swap_ints(int *a, int *b);
void max_heapify(int *array, size_t size, size_t base, size_t root);
void heap_sort(int *array, size_t size);
/**
* swap_ints - Swap two integers in an array.
* @a: The first integer to swap.
* @b: The second integer to swap.
*/
void swap_ints(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* max_heapify - Turn a binary tree into a complete binary heap.
* @array: An array of integers representing a binary tree.
* @size: The size of the array/tree.
* @base: The index of the base row of the tree.
* @root: The root node of the binary tree.
*/
void max_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_ints(array + root, array + large);
print_array(array, size);
max_heapify(array, size, base, large);
}
}
/**
* heap_sort - Sort an array of integers in ascending
* order using the heap sort algorithm.
* @array: An array of integers.
* @size: The size of the array.
*
* Description: Implements the sift-down heap sort
* algorithm. Prints the array after each swap.
*/
void heap_sort(int *array, size_t size)
{
int i;
if (array == NULL || size < 2)
return;
for (i = (size / 2) - 1; i >= 0; i--)
max_heapify(array, size, size, i);
for (i = size - 1; i > 0; i--)
{
swap_ints(array, array + i);
print_array(array, size);
max_heapify(array, size, i, 0);
}
}