Heap Sort is a fast and efficient comparison-based sorting algorithm that uses a binary heap data structure. A heap is a special kind of complete binary tree where the parent node is always greater (in a Max Heap) or smaller (in a Min Heap) than its child nodes.
Heap Sort works by first converting the input array into a Max Heap, where the largest value is at the root. Then it repeatedly removes the largest element (the root), places it at the end of the array, and rebuilds the heap with the remaining elements. This process continues until all elements are sorted.
A Max Heap is a binary tree that satisfies:
In Heap Sort, the array is treated as a binary tree using indices:
2*i + 1
2*i + 2
(i - 1) / 2
Case | Time Complexity |
---|---|
Best | O(n log n) |
Average | O(n log n) |
Worst | O(n log n) |
#include <iostream>
using namespace std;
// Function to heapify a subtree rooted at index i
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If left child is larger than root
if (left < n && arr[left] > arr[largest])
largest = left;
// If right child is larger than current largest
if (right < n && arr[right] > arr[largest])
largest = right;
// If largest is not the root
if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
// Main heap sort function
void heapSort(int arr[], int n) {
// Step 1: Build Max Heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Step 2: Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);
// Call heapify on reduced heap
heapify(arr, i, 0);
}
}
// Utility function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main function
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
heapSort(arr, n);
cout << "Sorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
12 11 13 5 6 7
Sorted array:
5 6 7 11 12 13
Let’s sort the array:
[12, 11, 13, 5, 6, 7]
Transform the array into a Max Heap:
[13, 11, 12, 5, 6, 7]
(Heapify from bottom up — ensure all parent nodes are larger than their children)
Start extracting the max value (root of the heap):
[7, 11, 12, 5, 6, 13]
[12, 11, 7, 5, 6, 13]
[6, 11, 7, 5, 12, 13]
[11, 6, 7, 5, 12, 13]
[5, 6, 7, 11, 12, 13]