Speed:
Heap Sort
Time: O(n log n)Space: O(1)Not Stable
🏔️How Heap Sort Works
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It works by first building a max heap from the input data, then repeatedly extracting the maximum element and placing it at the end of the sorted portion.
The algorithm consists of two main phases:
- Heapify: Build a max heap from the unsorted array
- Extract-Max: Repeatedly remove the root (max element) and restore heap property
- The extracted elements form the sorted array in descending order
- Since we want ascending order, we place elements at the end of the array
💻Implementation
🔍Heap Properties & Analysis
Heap Structure
- • Complete binary tree
- • Parent at index i, children at 2i+1 and 2i+2
- • Max heap: parent ≥ children
- • Height: O(log n)
Complexity Analysis
- • Build heap: O(n)
- • Extract max: O(log n)
- • Total: O(n log n)
- • Space: O(1) in-place
✅ Advantages
- • Guaranteed O(n log n) worst-case
- • In-place sorting (O(1) space)
- • Consistent performance across all inputs
- • Good cache performance
❌ Disadvantages
- • Not stable (doesn't preserve order)
- • Slower than quicksort in average case
- • Complex implementation
- • Poor performance on small arrays