7.1Heap with an Array
Heap sort
If you call remove the minimum again and again, the values come out from smallest to largest. That is a sorting algorithm. Heap sort applies the idea inside the array itself, with no extra array. It needs one small change: for ascending order a max-heap is used.
- Why a max-heap is built to sort in ascending order
- How the array splits into two parts: the heap at the front and the sorted part at the end
- How long heap sort takes and when it is chosen
1Idea
Heap sort has two phases. First the array is turned into a max-heap in place with heapify; the largest value reaches the root, arr[0]. Then this step is repeated: the root swaps with the last element of the heap. The largest value is now at the end of the array, in its final place. The heap shrinks by one, and the value that came to the root is sifted down to fix the heap.
Why a max-heap? Each value taken out goes to the end of the heap, the right end of the array. The right end has to fill with the largest values first so that the array ends up in ascending order. With a min-heap the smallest value would go to the end and the array would be sorted in descending order.
At every moment the array is in two parts: the first last elements are the heap, and the part on the right holds sorted values in their final places. Each step the heap shrinks by one and the sorted part grows by one. When the heap is down to one element, that element is the smallest and the array is sorted.
The code uses the max-heap version of sift down: the larger of the two children is chosen and the comparisons flip direction. The function also takes n, which says that the heap is the first n elements, not the whole array.
Heap sort is not stable: equal values may change order. It uses no extra memory and takes O(n log n) even in the worst case. In practice it is often slower than quicksort, but quicksort's worst case is O(n²), so some libraries add heap sort as a safety net for it.
2Step by step
The array in the drawing is 4, 10, 3, 5, 1. The part of the array that is a heap is drawn as a tree on top; values that are sorted into their final place turn green and leave the tree.
- Start: 4, 10, 3, 5, 1. First a max-heap is built; for 5 elements the loop starts at index
5/2 - 1 = 1. i = 1: 10's children are 5 and 1. 10 is larger than both; no swap.i = 0: 4's larger child is 10; they swap. 4 goes down a level and swaps once more with its larger child, 5. The max-heap is ready: 10, 5, 3, 4, 1.last = 4: the 10 at the root swaps with the last element, 1. 10 is at the end of the array, in its final place. The heap is now the first 4 elements.- The 1 that came to the root is sifted down: it swaps first with 5, then with 4. Heap: 5, 4, 3, 1.
last = 3: the 5 at the root swaps with 1. 5 is in its final place too. The heap is the first 3 elements.- 1 is sifted down and swaps with its larger child, 4. Heap: 4, 1, 3.
last = 2: 4 and 3 swap. The heap is the first 2 elements: 3, 1.- 3 is sifted down: its only child, 1, is smaller; no swap.
last = 1: 3 and 1 swap. The heap is down to one element; the loop ends.- The array is sorted: 1, 3, 4, 5, 10. No extra array was used.
void maxSiftDown(int arr[], int n, int i) { while (true) { int largest = i; int 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) return; int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; i = largest; }} void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) { maxSiftDown(arr, n, i); // 1. build a max-heap } for (int last = n - 1; last > 0; last--) { int temp = arr[0]; // 2. move the largest to the end arr[0] = arr[last]; arr[last] = temp; maxSiftDown(arr, last, 0); // fix the heap that is left }}static void maxSiftDown(int[] arr, int n, int i) { while (true) { int largest = i; int 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) return; int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; i = largest; }} static void heapSort(int[] arr) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) { maxSiftDown(arr, n, i); // 1. build a max-heap } for (int last = n - 1; last > 0; last--) { int temp = arr[0]; // 2. move the largest to the end arr[0] = arr[last]; arr[last] = temp; maxSiftDown(arr, last, 0); // fix the heap that is left }}def max_sift_down(arr, n, i): while True: largest = i left, right = 2 * i + 1, 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: return arr[i], arr[largest] = arr[largest], arr[i] i = largest def heap_sort(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): max_sift_down(arr, n, i) # 1. build a max-heap for last in range(n - 1, 0, -1): arr[0], arr[last] = arr[last], arr[0] # 2. move the largest to the end max_sift_down(arr, last, 0) # fix the heap that is leftThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Building the heap takes O(n). Then the root is moved to the end and sifted down n - 1 times; each costs O(log n). Total O(n log n). The time is the same in the best, average and worst case.
The sorting happens inside the array; a few variables are enough. Sift down is a loop, so the call stack does not grow either.
Simple methods such as selection sort or bubble sort take O(n²). Merge sort is O(n log n) too but needs an extra array of n elements. Heap sort combines the good parts: O(n log n) and O(1) extra memory.
4Common mistake
A common mistake is calling sift down on the whole array in the second phase:
maxSiftDown(arr, n, 0); // wrong: it should be last, not nThe large values already moved to the end still count as part of the heap, and sift down brings them back up to the root. The heap must shrink at every step; in the second phase the limit is last.
5Try it
Which heap does heap sort build in its first phase when sorting in ascending order?
The answer is B. Each step the root goes to the end of the array. For the end to fill with the largest value, the root must hold the largest value: a max-heap. With a min-heap the array would end up in descending order.
Show the answer
The answer is B. Each step the root goes to the end of the array. For the end to fill with the largest value, the root must hold the largest value: a max-heap. With a min-heap the array would end up in descending order.
In the max-heap 8, 3, 7, 1, 2, what is the array after the first removal step (root to the end, then sift down)?
The answer is A. 8 and 2 swap: 2, 3, 7, 1, 8. The heap is now the first 4 elements. 2's children are 3 and 7; the larger is 7, and they swap: 7, 3, 2, 1, 8. 2 is now in cell 2; cells 5 and 6, its would-be children, are outside the heap.
Show the answer
The answer is A. 8 and 2 swap: 2, 3, 7, 1, 8. The heap is now the first 4 elements. 2's children are 3 and 7; the larger is 7, and they swap: 7, 3, 2, 1, 8. 2 is now in cell 2; cells 5 and 6, its would-be children, are outside the heap.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.