Complexity Analysis
Heap sort has consistent, predictable performance.
Time Complexity
All Cases: O(n log n)
- Build heap: O(n) - linear time
- Extract n elements: O(n log n) - each extraction is O(log n)
- Total: O(n log n)
Space Complexity
O(1) - Constant Space
- Sorts in-place
- Only uses a few variables
- No extra arrays needed
Why O(n log n)?
- Build heap: O(n) - bottom-up heapify is efficient
- Extract n times: n × O(log n) = O(n log n)
- Total: O(n) + O(n log n) = O(n log n)
Comparison with Other Algorithms
**Advantages:**
• Guaranteed O(n log n)
• In-place (O(1) space)
• No worst-case scenario
• Predictable performance
**Disadvantages:**
• Not stable
• Slower than quicksort in practice
• More complex than simple sorts
**Advantages:**
• Guaranteed O(n log n)
• Stable algorithm
• Simple to understand
**Disadvantages:**
• O(n) extra space
• Not in-place
• More memory overhead
**Advantages:**
• O(n log n) average
• Fast in practice
• In-place (O(log n) space)
• Good cache performance
**Disadvantages:**
• O(n²) worst case
• Not stable
• Performance depends on pivot
When to Use
Heap sort is ideal when:
- You need guaranteed O(n log n) performance
- Memory is limited (in-place)
- You want to avoid worst-case scenarios
- Building priority queues
Advantages
- Guaranteed performance: Always O(n log n)
- In-place: Only O(1) extra space
- No worst case: Consistent performance
- No recursion: Can be iterative
Disadvantages
- Not stable: May change relative order
- Slower constants: More operations than quicksort
- Complex: More complex than simple sorts
- Cache performance: Not as cache-friendly as quicksort
What’s Next?
Let’s test your understanding with practice problems and a quiz.
Progress 86%
Page 6 of 7
← Previous
→ Next