|
| 1 | +#include "sort.h" |
| 2 | + |
| 3 | +void swap_ints(int *a, int *b); |
| 4 | +void max_heapify(int *array, size_t size, size_t base, size_t root); |
| 5 | +void heap_sort(int *array, size_t size); |
| 6 | + |
| 7 | +/** |
| 8 | + * swap_ints - Swap two integers in an array. |
| 9 | + * @a: The first integer to swap. |
| 10 | + * @b: The second integer to swap. |
| 11 | + */ |
| 12 | +void swap_ints(int *a, int *b) |
| 13 | +{ |
| 14 | + int tmp; |
| 15 | + |
| 16 | + tmp = *a; |
| 17 | + *a = *b; |
| 18 | + *b = tmp; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * max_heapify - Turn a binary tree into a complete binary heap. |
| 23 | + * @array: An array of integers representing a binary tree. |
| 24 | + * @size: The size of the array/tree. |
| 25 | + * @base: The index of the base row of the tree. |
| 26 | + * @root: The root node of the binary tree. |
| 27 | + */ |
| 28 | +void max_heapify(int *array, size_t size, size_t base, size_t root) |
| 29 | +{ |
| 30 | + size_t left, right, large; |
| 31 | + |
| 32 | + left = 2 * root + 1; |
| 33 | + right = 2 * root + 2; |
| 34 | + large = root; |
| 35 | + |
| 36 | + if (left < base && array[left] > array[large]) |
| 37 | + large = left; |
| 38 | + if (right < base && array[right] > array[large]) |
| 39 | + large = right; |
| 40 | + |
| 41 | + if (large != root) |
| 42 | + { |
| 43 | + swap_ints(array + root, array + large); |
| 44 | + print_array(array, size); |
| 45 | + max_heapify(array, size, base, large); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * heap_sort - Sort an array of integers in ascending |
| 51 | + * order using the heap sort algorithm. |
| 52 | + * @array: An array of integers. |
| 53 | + * @size: The size of the array. |
| 54 | + * |
| 55 | + * Description: Implements the sift-down heap sort |
| 56 | + * algorithm. Prints the array after each swap. |
| 57 | + */ |
| 58 | +void heap_sort(int *array, size_t size) |
| 59 | +{ |
| 60 | + int i; |
| 61 | + |
| 62 | + if (array == NULL || size < 2) |
| 63 | + return; |
| 64 | + |
| 65 | + for (i = (size / 2) - 1; i >= 0; i--) |
| 66 | + max_heapify(array, size, size, i); |
| 67 | + |
| 68 | + for (i = size - 1; i > 0; i--) |
| 69 | + { |
| 70 | + swap_ints(array, array + i); |
| 71 | + print_array(array, size); |
| 72 | + max_heapify(array, size, i, 0); |
| 73 | + } |
| 74 | +} |
0 commit comments