Heap Sort is a highly efficient comparison-based sorting algorithm that uses a binary heap data structure. It treats the input array as a complete binary tree and repeatedly removes the largest (or smallest) element from the heap and rebuilds the heap until the array is sorted.
A heap is a special binary tree:
Heap Sort usually uses a Max Heap to sort in ascending order.
| Case | Time Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
✅ Efficient for large datasets
✅ Good when O(n log n) time is required with constant space
❌ Avoid when stable sort is needed (e.g. preserving the order of equal elements)
public class HeapSortExample {
public static void heapSort(int[] arr) {
int n = arr.length;
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from heap one by one
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Heapify reduced heap
heapify(arr, i, 0);
}
}
public static void heapify(int[] arr, int heapSize, int rootIndex) {
int largest = rootIndex;
int leftChild = 2 * rootIndex + 1;
int rightChild = 2 * rootIndex + 2;
// If left child is larger
if (leftChild < heapSize && arr[leftChild] > arr[largest]) {
largest = leftChild;
}
// If right child is larger
if (rightChild < heapSize && arr[rightChild] > arr[largest]) {
largest = rightChild;
}
// If root is not largest
if (largest != rootIndex) {
int swap = arr[rootIndex];
arr[rootIndex] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected subtree
heapify(arr, heapSize, largest);
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
System.out.println("Original array:");
printArray(arr);
heapSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
12 11 13 5 6 7
Sorted array:
5 6 7 11 12 13
[12, 11, 13, 5, 6, 7]
Convert the array into a Max Heap:
[13, 11, 12, 5, 6, 7]
How?
n/2 - 1 = 2 (last non-leaf node)heapify(2) → already OKheapify(1) → [13, 11, 12, 5, 6, 7]heapify(0) → 12 vs 13 → swap → [13, 11, 12, 5, 6, 7]Swap root with last element, reduce heap size, heapify again.
[13, 11, 12, 5, 6, 7][7, 11, 12, 5, 6, 13][12, 11, 7, 5, 6, 13][12, 11, 7, 5, 6, 13][6, 11, 7, 5, 12, 13][11, 6, 7, 5, 12, 13][11, 6, 7, 5, 12, 13][5, 6, 7, 11, 12, 13]Repeat until the array is sorted.
[5, 6, 7, 11, 12, 13]