C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
heap_sort.c
Go to the documentation of this file.
1/**
2 * @file heap_sort.c
3 * @brief In-place heap sort. O(n log n) worst case, O(1) auxiliary memory.
4 *
5 * Step 1: build a max-heap in place from the input (linear time via
6 * Floyd's bottom-up sift-down).
7 * Step 2: repeatedly swap arr[0] (max) with arr[end] and sift-down the
8 * shrinking heap; the sorted suffix grows from the right.
9 *
10 * Re-uses heap_sift_down_max from data_structures/heap.
11 */
12
13#include "../../data_structures/heap/heap.h"
14#include "sorts.h"
15
16void heap_sort_ints(int *arr, size_t n) {
17 if (n <= 1) return;
18
19 /* Build max-heap. */
20 for (size_t i = n / 2; i > 0; i--) {
21 heap_sift_down_max(arr, i - 1, n);
22 }
23
24 /* Extract elements one by one — sorted suffix grows from arr[n-1] leftward. */
25 for (size_t end = n - 1; end > 0; end--) {
26 int tmp = arr[0]; arr[0] = arr[end]; arr[end] = tmp;
27 heap_sift_down_max(arr, 0, end);
28 }
29}
30
31/* ── String variant: max-heap on strcmp comparisons ─────────────────── */
32
33#include <string.h>
34
35static void sift_down_max_str(char **arr, size_t i, size_t n) {
36 while (1) {
37 size_t left = 2 * i + 1;
38 size_t right = 2 * i + 2;
39 size_t largest = i;
40 if (left < n && strcmp(arr[left], arr[largest]) > 0) largest = left;
41 if (right < n && strcmp(arr[right], arr[largest]) > 0) largest = right;
42 if (largest == i) break;
43 char *tmp = arr[i]; arr[i] = arr[largest]; arr[largest] = tmp;
44 i = largest;
45 }
46}
47
48void heap_sort_strings(char **arr, size_t n) {
49 if (n <= 1) return;
50 for (size_t i = n / 2; i > 0; i--) sift_down_max_str(arr, i - 1, n);
51 for (size_t end = n - 1; end > 0; end--) {
52 char *tmp = arr[0]; arr[0] = arr[end]; arr[end] = tmp;
53 sift_down_max_str(arr, 0, end);
54 }
55}
void heap_sift_down_max(int *arr, size_t i, size_t n)
Definition heap.c:103
static void sift_down_max_str(char **arr, size_t i, size_t n)
Definition heap_sort.c:35
void heap_sort_ints(int *arr, size_t n)
Definition heap_sort.c:16
void heap_sort_strings(char **arr, size_t n)
Definition heap_sort.c:48
Unified header for all sorting algorithms.