11.7 Heap sort¶
Tip
Before reading this section, work through the chapter on heaps.
Heap sort is an efficient sorting algorithm based on the heap data structure. We can implement it with two operations we have already seen: building a heap and removing its root.
- Build a min-heap from the input array. The smallest element is now at the root.
- Repeatedly remove the root and record each element as it comes out. The resulting sequence is in ascending order.
This approach works, but it requires an extra array to store the elements removed from the heap. In practice, we usually use a more space-efficient implementation.
11.7.1 How the algorithm works¶
For an array of length \(n\), heap sort proceeds as shown below.
- Build a max-heap from the input array. The largest element is now at the root.
- Swap the root (the first element) with the last element of the heap. This reduces the heap size by \(1\) and increases the number of sorted elements by \(1\).
- Sift down from the root to restore the heap property.
- Repeat steps
2.and3.. After \(n - 1\) rounds, the array is sorted.
Tip
Removing the root of a heap also includes steps 2. and 3., with the additional step of popping the element.
Figure 11-12 Heap sort steps
Description of Figure 11-12: In-place heap sort: move each maximum to the right end
Build a max-heap, then repeatedly swap its root with the last active element and shrink the heap. This sorts the six elements into [1, 1, 2, 3, 4, 5].
The diagram starts with the heap already built as [5, 4, 3, 1, 1, 2]. It does not show the input order before heap construction. In a max-heap, every parent is at least as large as either child. After the heap is restored, its root is the largest active element.
The binary tree at upper left corresponds to the array below in level order, with indices starting at 0. The left and right children of index i are at 2i+1 and 2i+2, respectively. Only indices within the active range belong to the heap. Green nodes mark the active heap and gray nodes the sorted range on the right.
To extract the maximum, swap the root with the last (rightmost) element of the active heap. This places the maximum in the gray sorted suffix on the right. Then sift down from the root within the shortened green prefix only.
When a node turns gray and joins the sorted range, its connecting edge in the tree on the left disappears. It takes no further part in sift-down comparisons, but the element stays in place in the array below. Shrinking the heap removes no elements from the array.
Initial max-heap built
The active heap covers indices 0 through 5. Its root, 5 at index 0, has children 4 and 3. Both children of 4 are 1, and the left child of 3 is the last heap element, 2. Now nums = [5, 4, 3, 1, 1, 2], with no sorted suffix yet.
Swap the root, 5, to the end of the array
Swap the root, 5 at index 0, with the last heap element, 2 at index 5. The maximum, 5, is fixed at index 5 and turns gray. The new root, 2, is smaller than its children 4 and 3, so the heap needs a sift-down. Now nums = [2, 4, 3, 1, 1, 5]. The active heap range is [0, 4], and the sorted suffix is [5].
Sift down to restore the five-element max-heap
The root, 2, is smaller than its larger child, 4, so the heap needs repair. Of the root and its children 4 and 3, choose the largest, 4, and swap it with 2. At index 1, the 2 is at least as large as both its children, each 1, so it stops sinking. The five-element heap is restored. Now nums = [4, 2, 3, 1, 1, 5]. The active heap range is [0, 4], and the sorted suffix is [5].
Swap the root, 4, to index 4
Swap the root, 4, with the 1 at the end of the active heap (index 4), fixing 4 at index 4. The new root, 1, is smaller than its children 2 and 3. Now nums = [1, 2, 3, 1, 4, 5]. The active heap range is [0, 3], and the sorted suffix is [4, 5].
Sift down to restore the four-element max-heap
The root, 1, is smaller than its larger child, 3. Compare the root with its children 2 and 3. Swap the largest, the right child 3, with the root. The 1 moves down to index 2, a leaf, restoring the four-element max-heap. Now nums = [3, 2, 1, 1, 4, 5]. The active heap range is [0, 3], and the sorted suffix is [4, 5].
Swap the root, 3, to index 3
Swap the root, 3, with the 1 at the end of the active heap (index 3), fixing 3 at the left end of the sorted suffix. The root, 1, is now smaller than its left child, 2. Now nums = [1, 2, 1, 3, 4, 5]. The active heap range is [0, 2], and the sorted suffix is [3, 4, 5].
Sift down to restore the three-element max-heap
The root, 1, is smaller than its larger child, 2, so the heap needs repair. Compare the root with its children 2 and 1. Swap the largest, the left child 2, with the root to restore the three-element heap [2, 1, 1]. Now nums = [2, 1, 1, 3, 4, 5]. The active heap range is [0, 2], and the sorted suffix is [3, 4, 5].
Swap the root, 2, to index 2
Swap the root, 2, with the 1 at the end of the active heap (index 2), adding 2 to the sorted suffix. Both remaining elements are 1. Now nums = [1, 1, 2, 3, 4, 5]. The active heap range is [0, 1], and the sorted suffix is [2, 3, 4, 5].
Equal 1s need no swap during the sift-down check
In the two-element heap, the sift-down check compares the root, 1, with its left child, also 1. The parent is already at least as large as its child. The figure highlights the comparison path, but no swap occurs and the values stay the same. Now nums = [1, 1, 2, 3, 4, 5]. The active heap range is [0, 1], and the sorted suffix is [2, 3, 4, 5].
Make the final swap between the root and last active element
Swap indices 0 and 1 in the two-element heap. Both hold 1, so the array values stay the same. The 1 at index 1 turns gray and joins the sorted suffix. Now nums = [1, 1, 2, 3, 4, 5]. The active heap range is [0, 0], and the sorted suffix is [1, 2, 3, 4, 5].
A single-node heap needs no sift-down
The active heap now consists only of the root, 1 at index 0. It has no active child to compare, so sifting down ends immediately. The figure still highlights the root in green, with five gray items to its right. Now nums = [1, 1, 2, 3, 4, 5]. The active heap range is [0, 0], and the sorted suffix is [1, 2, 3, 4, 5].
The last element is already in place, completing the sort
The last remaining element, 1 at index 0, is the array minimum and needs no extraction. It too turns gray, so all six elements are in the sorted range. Now nums = [1, 1, 2, 3, 4, 5]. The active heap awaiting processing is empty, and all six items are sorted.
The implementation uses the same sift-down function, sift_down(), as the chapter on heaps. Because the heap shrinks each time we extract its maximum, we add a length parameter \(n\) to sift_down() to specify the current size of the heap:
def sift_down(nums: list[int], n: int, i: int):
"""Sift down from node i in a heap of size n"""
while True:
# Let ma be the index of the largest of nodes i, l, and r
l = 2 * i + 1
r = 2 * i + 2
ma = i
if l < n and nums[l] > nums[ma]:
ma = l
if r < n and nums[r] > nums[ma]:
ma = r
# Stop if i is the largest or both child indices l and r are out of bounds
if ma == i:
break
# Swap the two nodes
nums[i], nums[ma] = nums[ma], nums[i]
# Continue sifting down
i = ma
def heap_sort(nums: list[int]):
"""Heap sort"""
# Build the heap by sifting down from each non-leaf node
for i in range(len(nums) // 2 - 1, -1, -1):
sift_down(nums, len(nums), i)
# Extract the maximum from the heap in each of n-1 rounds
for i in range(len(nums) - 1, 0, -1):
# Swap the root and rightmost leaf (the first and last elements)
nums[0], nums[i] = nums[i], nums[0]
# Sift down from the root
sift_down(nums, i, 0)
/* Sift down from node i in a heap of size n */
void siftDown(vector<int> &nums, int n, int i) {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i) {
break;
}
// Swap the two nodes
swap(nums[i], nums[ma]);
// Continue sifting down
i = ma;
}
}
/* Heap sort */
void heapSort(vector<int> &nums) {
// Build the heap by sifting down from each non-leaf node
for (int i = nums.size() / 2 - 1; i >= 0; --i) {
siftDown(nums, nums.size(), i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (int i = nums.size() - 1; i > 0; --i) {
// Swap the root and rightmost leaf (the first and last elements)
swap(nums[0], nums[i]);
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
void siftDown(int[] nums, int n, int i) {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i)
break;
// Swap the two nodes
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
// Continue sifting down
i = ma;
}
}
/* Heap sort */
void heapSort(int[] nums) {
// Build the heap by sifting down from each non-leaf node
for (int i = nums.length / 2 - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (int i = nums.length - 1; i > 0; i--) {
// Swap the root and rightmost leaf (the first and last elements)
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
void SiftDown(int[] nums, int n, int i) {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i)
break;
// Swap the two nodes
(nums[ma], nums[i]) = (nums[i], nums[ma]);
// Continue sifting down
i = ma;
}
}
/* Heap sort */
void HeapSort(int[] nums) {
// Build the heap by sifting down from each non-leaf node
for (int i = nums.Length / 2 - 1; i >= 0; i--) {
SiftDown(nums, nums.Length, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (int i = nums.Length - 1; i > 0; i--) {
// Swap the root and rightmost leaf (the first and last elements)
(nums[i], nums[0]) = (nums[0], nums[i]);
// Sift down from the root
SiftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
func siftDown(nums *[]int, n, i int) {
for true {
// Let ma be the index of the largest of nodes i, l, and r
l := 2*i + 1
r := 2*i + 2
ma := i
if l < n && (*nums)[l] > (*nums)[ma] {
ma = l
}
if r < n && (*nums)[r] > (*nums)[ma] {
ma = r
}
// Stop if i is the largest or both child indices l and r are out of bounds
if ma == i {
break
}
// Swap the two nodes
(*nums)[i], (*nums)[ma] = (*nums)[ma], (*nums)[i]
// Continue sifting down
i = ma
}
}
/* Heap sort */
func heapSort(nums *[]int) {
// Build the heap by sifting down from each non-leaf node
for i := len(*nums)/2 - 1; i >= 0; i-- {
siftDown(nums, len(*nums), i)
}
// Extract the maximum from the heap in each of n-1 rounds
for i := len(*nums) - 1; i > 0; i-- {
// Swap the root and rightmost leaf (the first and last elements)
(*nums)[0], (*nums)[i] = (*nums)[i], (*nums)[0]
// Sift down from the root
siftDown(nums, i, 0)
}
}
/* Sift down from node i in a heap of size n */
func siftDown(nums: inout [Int], n: Int, i: Int) {
var i = i
while true {
// Let ma be the index of the largest of nodes i, l, and r
let l = 2 * i + 1
let r = 2 * i + 2
var ma = i
if l < n, nums[l] > nums[ma] {
ma = l
}
if r < n, nums[r] > nums[ma] {
ma = r
}
// Stop if i is the largest or both child indices l and r are out of bounds
if ma == i {
break
}
// Swap the two nodes
nums.swapAt(i, ma)
// Continue sifting down
i = ma
}
}
/* Heap sort */
func heapSort(nums: inout [Int]) {
// Build the heap by sifting down from each non-leaf node
for i in stride(from: nums.count / 2 - 1, through: 0, by: -1) {
siftDown(nums: &nums, n: nums.count, i: i)
}
// Extract the maximum from the heap in each of n-1 rounds
for i in nums.indices.dropFirst().reversed() {
// Swap the root and rightmost leaf (the first and last elements)
nums.swapAt(0, i)
// Sift down from the root
siftDown(nums: &nums, n: i, i: 0)
}
}
/* Sift down from node i in a heap of size n */
function siftDown(nums, n, i) {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
let l = 2 * i + 1;
let r = 2 * i + 2;
let ma = i;
if (l < n && nums[l] > nums[ma]) {
ma = l;
}
if (r < n && nums[r] > nums[ma]) {
ma = r;
}
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma === i) {
break;
}
// Swap the two nodes
[nums[i], nums[ma]] = [nums[ma], nums[i]];
// Continue sifting down
i = ma;
}
}
/* Heap sort */
function heapSort(nums) {
// Build the heap by sifting down from each non-leaf node
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (let i = nums.length - 1; i > 0; i--) {
// Swap the root and rightmost leaf (the first and last elements)
[nums[0], nums[i]] = [nums[i], nums[0]];
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
function siftDown(nums: number[], n: number, i: number): void {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
let l = 2 * i + 1;
let r = 2 * i + 2;
let ma = i;
if (l < n && nums[l] > nums[ma]) {
ma = l;
}
if (r < n && nums[r] > nums[ma]) {
ma = r;
}
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma === i) {
break;
}
// Swap the two nodes
[nums[i], nums[ma]] = [nums[ma], nums[i]];
// Continue sifting down
i = ma;
}
}
/* Heap sort */
function heapSort(nums: number[]): void {
// Build the heap by sifting down from each non-leaf node
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (let i = nums.length - 1; i > 0; i--) {
// Swap the root and rightmost leaf (the first and last elements)
[nums[0], nums[i]] = [nums[i], nums[0]];
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
void siftDown(List<int> nums, int n, int i) {
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma]) ma = l;
if (r < n && nums[r] > nums[ma]) ma = r;
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i) break;
// Swap the two nodes
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
// Continue sifting down
i = ma;
}
}
/* Heap sort */
void heapSort(List<int> nums) {
// Build the heap by sifting down from each non-leaf node
for (int i = nums.length ~/ 2 - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (int i = nums.length - 1; i > 0; i--) {
// Swap the root and rightmost leaf (the first and last elements)
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
fn sift_down(nums: &mut [i32], n: usize, mut i: usize) {
loop {
// Let ma be the index of the largest of nodes i, l, and r
let l = 2 * i + 1;
let r = 2 * i + 2;
let mut ma = i;
if l < n && nums[l] > nums[ma] {
ma = l;
}
if r < n && nums[r] > nums[ma] {
ma = r;
}
// Stop if i is the largest or both child indices l and r are out of bounds
if ma == i {
break;
}
// Swap the two nodes
nums.swap(i, ma);
// Continue sifting down
i = ma;
}
}
/* Heap sort */
fn heap_sort(nums: &mut [i32]) {
// Build the heap by sifting down from each non-leaf node
for i in (0..nums.len() / 2).rev() {
sift_down(nums, nums.len(), i);
}
// Extract the maximum from the heap in each of n-1 rounds
for i in (1..nums.len()).rev() {
// Swap the root and rightmost leaf (the first and last elements)
nums.swap(0, i);
// Sift down from the root
sift_down(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
void siftDown(int nums[], int n, int i) {
while (1) {
// Let ma be the index of the largest of nodes i, l, and r
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i) {
break;
}
// Swap the two nodes
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
// Continue sifting down
i = ma;
}
}
/* Heap sort */
void heapSort(int nums[], int n) {
// Build the heap by sifting down from each non-leaf node
for (int i = n / 2 - 1; i >= 0; --i) {
siftDown(nums, n, i);
}
// Extract the maximum from the heap in each of n-1 rounds
for (int i = n - 1; i > 0; --i) {
// Swap the root and rightmost leaf (the first and last elements)
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// Sift down from the root
siftDown(nums, i, 0);
}
}
/* Sift down from node i in a heap of size n */
fun siftDown(nums: IntArray, n: Int, li: Int) {
var i = li
while (true) {
// Let ma be the index of the largest of nodes i, l, and r
val l = 2 * i + 1
val r = 2 * i + 2
var ma = i
if (l < n && nums[l] > nums[ma])
ma = l
if (r < n && nums[r] > nums[ma])
ma = r
// Stop if i is the largest or both child indices l and r are out of bounds
if (ma == i)
break
// Swap the two nodes
val temp = nums[i]
nums[i] = nums[ma]
nums[ma] = temp
// Continue sifting down
i = ma
}
}
/* Heap sort */
fun heapSort(nums: IntArray) {
// Build the heap by sifting down from each non-leaf node
for (i in nums.size / 2 - 1 downTo 0) {
siftDown(nums, nums.size, i)
}
// Extract the maximum from the heap in each of n-1 rounds
for (i in nums.size - 1 downTo 1) {
// Swap the root and rightmost leaf (the first and last elements)
val temp = nums[0]
nums[0] = nums[i]
nums[i] = temp
// Sift down from the root
siftDown(nums, i, 0)
}
}
### Sift down from node i in a heap of size n ###
def sift_down(nums, n, i)
while true
# Let ma be the index of the largest of nodes i, l, and r
l = 2 * i + 1
r = 2 * i + 2
ma = i
ma = l if l < n && nums[l] > nums[ma]
ma = r if r < n && nums[r] > nums[ma]
# Stop if i is the largest or both child indices l and r are out of bounds
break if ma == i
# Swap the two nodes
nums[i], nums[ma] = nums[ma], nums[i]
# Continue sifting down
i = ma
end
end
### Heap sort ###
def heap_sort(nums)
# Build the heap by sifting down from each non-leaf node
(nums.length / 2 - 1).downto(0) do |i|
sift_down(nums, nums.length, i)
end
# Extract the maximum from the heap in each of n-1 rounds
(nums.length - 1).downto(1) do |i|
# Swap the root and rightmost leaf (the first and last elements)
nums[0], nums[i] = nums[i], nums[0]
# Sift down from the root
sift_down(nums, i, 0)
end
end
Visualize execution
11.7.2 Algorithm properties¶
- Time complexity: \(O(n \log n)\), nonadaptive. Building the heap takes \(O(n)\) time. Extracting its maximum takes \(O(\log n)\) time per round, for a total of \(n - 1\) rounds.
- Space complexity: \(O(1)\), in-place. The few index variables use \(O(1)\) space. Swaps and sift-down operations both work directly on the original array.
- Unstable. Swapping the root with the last element of the heap can change the relative order of equal elements.