NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Heap Sort in Data Structure

Heap sort builds a binary heap (max-heap for ascending sort) from the array, repeatedly swaps the root with the last unsorted element, reduces heap size by one, and heapifies the root. It runs in O(n log n) time across all cases with O(1) extra space.


Theory & Explanation

Heap Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure (specifically a max-heap for sorting in ascending order, or a min-heap for descending order). A max-heap is a complete binary tree where every parent node is greater than or equal to its child nodes. Heap Sort first converts the input array into a max-heap, then repeatedly moves the largest element (at the root) to the end of the array and restores the heap property on the remaining unsorted elements.

  • In-Place Sorting: Sorts the array directly in place using only a constant O(1) extra memory (iterative heapify) or O(log2 n) call-stack space (recursive heapify).
  • Guaranteed O(n log2 n) Time: Both heap construction and repeated extraction/heapify take O(n log2 n) time in best, average, and worst cases.
  • Not Stable: Swapping the root with the last element of the active heap can alter the relative order of equal keys.
  • Array Representation of Binary Heap (0-based indexing): For a node at index i, its left child is at 2i + 1, its right child is at 2i + 2, and its parent is at (i - 1) / 2.

2. How Heap Sort Works (Step-by-Step Algorithm)

  1. Build a Max-Heap: Start from the last non-leaf node at index i = (n / 2) - 1 down to 0, and call heapify(arr, n, i) so the entire array satisfies the max-heap property.
  2. Extract Maximum & Swap: Loop end from n - 1 down to 1:
    • Swap the root element arr[0] (largest in the heap) with arr[end] (last element of the unsorted region).
    • Shrink the active heap size to end and call heapify(arr, end, 0) to restore the max-heap property at the root.
  3. heapify(arr, heapSize, i) Procedure:
    • Assume largest = i, left = 2i + 1, and right = 2i + 2.
    • If left < heapSize and arr[left] > arr[largest], set largest = left.
    • If right < heapSize and arr[right] > arr[largest], set largest = right.
    • If largest != i, swap arr[i] and arr[largest], and recursively call heapify(arr, heapSize, largest).

3. Step-by-Step Example & Graphical Representation

Sort arr = [4, 10, 3, 5, 1] (n = 5) in ascending order:

  • Phase 1 — Build Max-Heap (i = 1 down to 0):
    • i = 1 (value 10): children are 5 (idx 3) and 1 (idx 4); 10 is already largest → [4, 10, 3, 5, 1].
    • i = 0 (value 4): children are 10 (idx 1) and 3 (idx 2) → swap 4 & 10 → [10, 4, 3, 5, 1]; then at idx 1 (4), swap with child 5 (idx 3) → Max-Heap: [10, 5, 3, 4, 1].
  • Phase 2 — Extract Max & Heapify:
    • Step 1 (end = 4): Swap arr[0] (10) and arr[4] (1) → [1, 5, 3, 4 | 10]; heapify root on size 4 → [5, 4, 3, 1 | 10].
    • Step 2 (end = 3): Swap arr[0] (5) and arr[3] (1) → [1, 4, 3 | 5, 10]; heapify root on size 3 → [4, 1, 3 | 5, 10].
    • Step 3 (end = 2): Swap arr[0] (4) and arr[2] (3) → [3, 1 | 4, 5, 10]; heapify root on size 2 → [3, 1 | 4, 5, 10].
    • Step 4 (end = 1): Swap arr[0] (3) and arr[1] (1) → [1, 3, 4, 5, 10] (sorted).

Graphical Representation: Stepwise Heap Sort on [4, 10, 3, 5, 1]

Heap Sort Trace (Ascending): Build Max-Heap → Swap Root with End → Heapify
Phase 1: Build Max-Heap from [4, 10, 3, 5, 1]
Max-Heap Array: [10, 5, 3, 4, 1]  |  Tree: Root 10 → children 5 & 3; 5 → children 4 & 1.
Extract 1 (end = 4)
Swap 10 & 1 → [1, 5, 3, 4 | 10]
Heapify(4, 0) → [5, 4, 3, 1 | 10]
Extract 2 (end = 3)
Swap 5 & 1 → [1, 4, 3 | 5, 10]
Heapify(3, 0) → [4, 1, 3 | 5, 10]
Extracts 3 & 4 (Final)
Extract 3 → [3, 1 | 4, 5, 10]
Extract 4 → [1, 3, 4, 5, 10] (Sorted)

4. Time & Space Complexity Analysis

Case Condition Time Complexity Exam Note
Best Case Any input of size n O(n log2 n) Building heap is O(n); extracting n items with heapify is O(n log n)
Average Case Randomly ordered elements O(n log2 n) Consistent logarithmic height ⌊log2 n⌋ for heapify operations
Worst Case Reverse-sorted or skewed input O(n log2 n) No quadratic worst case unlike naive Quick Sort

Auxiliary Space Complexity: O(1) with iterative heapify, or O(log2 n) recursion stack with recursive heapify.

5. C Program: Heap Sort

#include <stdio.h>

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

void heapify(int arr[], int n, int i) {
    int largest = i;
    int left = 2  i + 1;
    int right = 2  i + 2;

    if (left < n && arr[left] > arr[largest])
        largest = left;

    if (right < n && arr[right] > arr[largest])
        largest = right;

    if (largest != i) {
        swap(&arr[i], &arr[largest]);
        heapify(arr, n, largest);
    }
}

void heapSort(int arr[], int n) {
    // 1. Build max-heap
    for (int i = n / 2 - 1; i >= 0; i--) {
        heapify(arr, n, i);
    }

    // 2. Extract elements one by one from heap
    for (int i = n - 1; i > 0; i--) {
        swap(&arr[0], &arr[i]);
        heapify(arr, i, 0);
    }
}

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

int main() {
    int arr[] = {4, 10, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    heapSort(arr, n);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 4 10 3 5 1 
Sorted array (Ascending): 1 3 4 5 10 

6. Python Program: Heap Sort

def heapify(arr, n, i):
    largest = i
    left = 2  i + 1
    right = 2  i + 2

    if left < n and arr[left] > arr[largest]:
        largest = left

    if right < n and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest)


def heap_sort(arr):
    a = arr[:]
    n = len(a)

    # 1. Build max-heap
    for i in range(n // 2 - 1, -1, -1):
        heapify(a, n, i)

    # 2. Extract elements from heap one by one
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        heapify(a, end, 0)

    return a


if __name__ == "__main__":
    data = [4, 10, 3, 5, 1]
    print("Original array:", data)
    print("Sorted array (Ascending):", heap_sort(data))

Expected Output (Python):

Original array: [4, 10, 3, 5, 1]
Sorted array (Ascending): [1, 3, 4, 5, 10]
Advertisement
Advertisement