DSA — Heap Sort
What is Heap Sort?
Uses a binary heap to sort elements by building a max heap and extracting maximum.
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):
n = len(arr)
# Build max heap
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# Extract elements
for i in range(n - 1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
return arr
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
Characteristics
- Not stable
- In-place
- Consistent performance
- Good for priority queues
Mini Practice
- Implement heap sort
- Build max heap
- Sort in descending order
- Compare with quick sort
Up Next
Continue with Counting Sort — non-comparison sort.
Related Topics
Frequently Asked Questions about Heap Sort
What is Heap Sort in DSA?
Heap Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Heap Sort?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Heap Sort.
Why is Heap Sort important in DSA?
Heap Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.