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) orO(log2 n)call-stack space (recursive heapify). - Guaranteed
O(n log2 n)Time: Both heap construction and repeated extraction/heapify takeO(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 at2i + 1, its right child is at2i + 2, and its parent is at(i - 1) / 2.
2. How Heap Sort Works (Step-by-Step Algorithm)
- Build a Max-Heap: Start from the last non-leaf node at index
i = (n / 2) - 1down to0, and callheapify(arr, n, i)so the entire array satisfies the max-heap property. - Extract Maximum & Swap: Loop
endfromn - 1down to1:- Swap the root element
arr[0](largest in the heap) witharr[end](last element of the unsorted region). - Shrink the active heap size to
endand callheapify(arr, end, 0)to restore the max-heap property at the root.
- Swap the root element
heapify(arr, heapSize, i)Procedure:- Assume
largest = i,left = 2i + 1, andright = 2i + 2. - If
left < heapSizeandarr[left] > arr[largest], setlargest = left. - If
right < heapSizeandarr[right] > arr[largest], setlargest = right. - If
largest != i, swaparr[i]andarr[largest], and recursively callheapify(arr, heapSize, largest).
- Assume
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 = 1down to0):i = 1(value10): children are5(idx 3) and1(idx 4);10is already largest →[4, 10, 3, 5, 1].i = 0(value4): children are10(idx 1) and3(idx 2) → swap4&10→[10, 4, 3, 5, 1]; then at idx 1 (4), swap with child5(idx 3) → Max-Heap:[10, 5, 3, 4, 1].
- Phase 2 — Extract Max & Heapify:
- Step 1 (
end = 4): Swaparr[0](10) andarr[4](1) →[1, 5, 3, 4 | 10]; heapify root on size 4 →[5, 4, 3, 1 | 10]. - Step 2 (
end = 3): Swaparr[0](5) andarr[3](1) →[1, 4, 3 | 5, 10]; heapify root on size 3 →[4, 1, 3 | 5, 10]. - Step 3 (
end = 2): Swaparr[0](4) andarr[2](3) →[3, 1 | 4, 5, 10]; heapify root on size 2 →[3, 1 | 4, 5, 10]. - Step 4 (
end = 1): Swaparr[0](3) andarr[1](1) →[1, 3, 4, 5, 10](sorted).
- Step 1 (
Graphical Representation: Stepwise Heap Sort on [4, 10, 3, 5, 1]
Heapify(4, 0) → [5, 4, 3, 1 | 10]
Heapify(3, 0) → [4, 1, 3 | 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]