DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Sort an Array with Heap Sort

Learn how to sort an array with heap sort using a clear C program.

IntermediateHeap sortMax-heapIn-place sorting

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
5 6 7 11 12 13

COMPLETE C PROGRAM

Complete C implementation

dsa-heap-sort.c
Open in compiler
#include <stdio.h>

void heapify(int values[], int size, int root)
{
    int largest = root, left = 2 * root + 1, right = left + 1;
    if (left < size && values[left] > values[largest]) largest = left;
    if (right < size && values[right] > values[largest]) largest = right;
    if (largest != root) {
        int temporary = values[root]; values[root] = values[largest]; values[largest] = temporary;
        heapify(values, size, largest);
    }
}

int main(void)
{
    int values[] = {12, 11, 13, 5, 6, 7};
    int size = 6;
    for (int index = size / 2 - 1; index >= 0; index--) heapify(values, size, index);
    for (int end = size - 1; end > 0; end--) {
        int temporary = values[0]; values[0] = values[end]; values[end] = temporary;
        heapify(values, end, 0);
    }
    for (int index = 0; index < size; index++) printf("%d ", values[index]);
    putchar('\n');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

5 6 7 11 12 13
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Build a max-heap and repeatedly move its root to the end of the unsorted region.
  3. Display the computed result.

Build a max-heap and repeatedly move its root to the end of the unsorted region.

EFFICIENCY

Time and space complexity

Time complexity

O(n log n)

Auxiliary space

O(log n) recursion

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.