Heap Sort Algorithm in DSA Go - Time & Space Complexity
We want to understand how the time taken by Heap Sort changes as the list size grows.
How does the number of steps increase when sorting bigger lists?
Analyze the time complexity of the following code snippet.
func heapSort(arr []int) {
n := len(arr)
for i := n/2 - 1; i >= 0; i-- {
heapify(arr, n, i)
}
for i := n - 1; i > 0; i-- {
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
}
}
func heapify(arr []int, n, i int) {
largest := i
left := 2*i + 1
right := 2*i + 2
if left < n && arr[left] > arr[largest] {
largest = left
}
if right < n && arr[right] > arr[largest] {
largest = right
}
if largest != i {
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
}
}
This code builds a max heap from the array, then repeatedly swaps the largest element to the end and fixes the heap.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
heapifyfunction called multiple times to maintain the heap property. - How many times: The first loop calls
heapifyabout n/2 times; the second loop callsheapifyn-1 times, each potentially recursing down the heap.
As the list size grows, the number of operations grows more than just a simple multiple.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 heapify steps |
| 100 | About 700 to 800 heapify steps |
| 1000 | About 10,000 heapify steps |
Pattern observation: The operations grow roughly proportional to n times log n, meaning it grows faster than n but slower than n squared.
Time Complexity: O(n log n)
This means if the list doubles in size, the time to sort grows a bit more than double, but much less than four times.
[X] Wrong: "Heap Sort is as slow as bubble sort because it uses loops inside loops."
[OK] Correct: Heap Sort uses a smart tree structure to reduce repeated work, so it sorts much faster than simple nested loops.
Understanding Heap Sort's time complexity shows you can analyze efficient sorting methods, a key skill in many coding challenges.
"What if we used a min heap instead of a max heap? How would the time complexity change?"