Skip to content
Laviyx Learn

Try

DS Lab · Experiment 9

Heap sort

CSortingJNTUH R22 · CS306PC

Aim

To write a C program that sorts a list of integers in ascending order using heap sort, showing the max heap that is built and the array after each element is moved to its place.

Algorithm

  1. Read n and the n elements into an array. Think of the array as a complete binary tree: the children of index i are at 2i + 1 and 2i + 2.
  2. Heapify (n, i): find the largest of a[i] and its children that are inside the first n elements. If a child is larger, swap it with a[i] and heapify that child's position again.
  3. Build a max heap: call heapify for every non-leaf index from n/2 − 1 down to 0. Now a[0] is the largest element.
  4. For i from n − 1 down to 1: swap a[0] (the largest left) with a[i], so it goes to its final place at the end.
  5. Heapify (i, 0) to restore the max heap in the first i elements.
  6. Print the sorted array.

Program

C
#include <stdio.h>

#define MAX 50

void print_array(int a[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

/* Make the subtree rooted at index i a max heap,
   looking only at the first n elements */
void heapify(int a[], int n, int i) {
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < n && a[left] > a[largest]) {
        largest = left;
    }
    if (right < n && a[right] > a[largest]) {
        largest = right;
    }
    if (largest != i) {
        swap(&a[i], &a[largest]);
        heapify(a, n, largest);
    }
}

void heap_sort(int a[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--) {
        heapify(a, n, i);
    }
    printf("Max heap built:      ");
    print_array(a, n);

    for (int i = n - 1; i > 0; i--) {
        swap(&a[0], &a[i]);          /* largest goes to the end */
        heapify(a, i, 0);            /* restore heap in a[0..i-1] */
        printf("After placing %3d:   ", a[i]);
        print_array(a, n);
    }
}

int main(void) {
    int a[MAX], n;

    printf("Enter number of elements (1-%d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of elements\n");
        return 1;
    }
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("Invalid input\n");
            return 1;
        }
    }

    heap_sort(a, n);

    printf("Sorted list: ");
    print_array(a, n);
    return 0;
}

Output

Output
Enter number of elements (1-50): 7
Enter 7 elements: 4 10 3 5 1 15 8
Max heap built:      15 10 8 5 1 3 4 
After placing  15:   10 5 8 4 1 3 15 
After placing  10:   8 5 3 4 1 10 15 
After placing   8:   5 4 3 1 8 10 15 
After placing   5:   4 1 3 5 8 10 15 
After placing   4:   3 1 4 5 8 10 15 
After placing   3:   1 3 4 5 8 10 15 
Sorted list: 1 3 4 5 8 10 15 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The heap is not a separate tree in memory: it lives inside the same array. For index i, the left child is at 2i + 1, the right child at 2i + 2, and the parent at (i − 1) / 2.

In each "After placing" line, the elements from the placed one to the end of the array are already sorted, and the part before them is still a max heap.

Common mistakes

  • Using 1-based child formulas (2i and 2i + 1) with a 0-based C array. With index 0 as the root, the children are 2i + 1 and 2i + 2.

  • Calling heapify(a, n, 0) after each swap instead of heapify(a, i, 0). The heap must shrink, otherwise the sorted elements at the end are pulled back into it.

  • Building the heap from index 0 upwards. Heapify assumes both subtrees are already heaps, so the build must go from n/2 − 1 down to 0.

  • Comparing a[left] > a[i] and then a[right] > a[i] instead of comparing with a[largest], which can swap with the smaller child.

Viva questions

Try to answer each one aloud before you open it.

  • What is a max heap?

    A complete binary tree in which every node's value is greater than or equal to the values of its children. So the largest value is at the root.

  • What is the time complexity of heap sort?

    O(n log n) in the best, average and worst cases. Building the heap is O(n) and each of the n − 1 removals costs O(log n).

  • Is heap sort stable? Is it in-place?

    It is not stable, because swaps can change the order of equal elements. It is in-place: it needs only O(1) extra space.

  • Why does the heap building loop start at n/2 − 1?

    Elements from index n/2 onwards are leaves, and a single node is already a heap. So only the non-leaf nodes, 0 to n/2 − 1, need heapify.

  • Which heap would you use to sort in descending order?

    A min heap. Each step then moves the smallest remaining element to the end, giving descending order.

Learn the concepts

All Data Structures Lab experiments →