Heap sort in C: solved exercise with max heap

Heap sort in C: solved exercise with max heap

This exercise is scheduled for daily publication and follows the same didactic structure used across the site: clear statement, compilable code, and expected output.

Problem statement

Implement a practical example of the topic and validate the output in the console.

C solution

 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
#include <stdio.h>

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

void heapify(int a[], int n, int i) {
    int mayor = i, izq = 2 * i + 1, der = 2 * i + 2;
    if (izq < n && a[izq] > a[mayor]) mayor = izq;
    if (der < n && a[der] > a[mayor]) mayor = der;
    if (mayor != i) {
        swap(&a[i], &a[mayor]);
        heapify(a, n, mayor);
    }
}

void heap_sort(int a[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);
    for (int i = n - 1; i > 0; i--) {
        swap(&a[0], &a[i]);
        heapify(a, i, 0);
    }
}

int main(void) {
    int v[] = {4, 10, 3, 5, 1};
    int n = (int)(sizeof(v) / sizeof(v[0]));
    heap_sort(v, n);
    for (int i = 0; i < n; i++) printf("%d ", v[i]);
    printf("\n");
    return 0;
}

Expected output

1
1 3 4 5 10

Common mistakes

  • Not validating input and standard-library return values.
  • Ignoring edge cases (buffers, limits, null pointers).
  • Skipping basic compile/run verification.

Practical use

Heap sort guarantees O(n log n) in the worst case and needs no extra memory, making it ideal when space is constrained.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.