Skip to content

8.1   Heap

A heap is a complete binary tree that satisfies an ordering rule. The two main types are shown below.

  • Min-heap: For every parent-child pair, the parent's value \(\leq\) the child's value.
  • Max-heap: For every parent-child pair, the parent's value \(\geq\) the child's value.

Figure 8-1   Min-heaps and max-heaps

Description of Figure 8-1: Structure and ordering of min-heaps and max-heaps

The min-heap on the left and the max-heap on the right have the same shape, with opposite ordering rules for parents and children.

Both heaps are complete binary trees with 12 nodes. The first three levels are full, and the fourth has 5 consecutive nodes starting at the far left. The table lists the values level by level from top to bottom, reading each level from left to right. The level numbers come from these positions and do not appear in the figure.

Both trees have the same connections. Each root has two children, as does each node on the second level. From left to right on the third level, the first two nodes each have two children, the third has only a left child, and the fourth is a leaf. Together with the table, this identifies every parent-child connection.

Node values in each heap, from left to right by level
LevelMin-heapMax-heap
119
23, 28, 6
36, 4, 2, 66, 7, 5, 2
48, 7, 9, 6, 51, 4, 3, 6, 2

The labels below the trees give the ordering rules. In a min-heap, each parent's value is less than or equal to each child's. In a max-heap, it is greater than or equal to each child's. Equal values are allowed. For example, the right node on the second level of the min-heap and its left child both have value 2. Nodes on one level need not be sorted from left to right, and siblings can appear in either order.

Comparing each parent with its children level by level shows that the min-heap's root, 1, is the minimum value in its heap, and the max-heap's root, 9, is the maximum in its heap.

As a special case of a complete binary tree, a heap has the following properties.

  • The bottom level fills from left to right. Every other level is full.
  • The root of the tree is the top of the heap. The rightmost node on the bottom level is the last element of the heap.
  • In a max-heap the root holds the maximum value, and in a min-heap it holds the minimum.

8.1.1   Common heap operations

Many programming languages provide a priority queue, an abstract data structure that orders queue elements by priority.

Heaps commonly implement priority queues. A max-heap acts as a priority queue whose elements are removed from largest to smallest. From the user's perspective, we can treat a priority queue and a heap as equivalent here. This book uses the term “heap” for both.

Table 8-1 lists common heap operations. Method names depend on the programming language.

Table 8-1   Efficiency of heap operations

Method name Description Time complexity
push() Push an element onto the heap \(O(\log n)\)
pop() Pop the root \(O(\log n)\)
peek() Access the root element (the maximum in a max-heap or the minimum in a min-heap) \(O(1)\)
size() Get the number of elements in the heap \(O(1)\)
isEmpty() Check whether the heap is empty \(O(1)\)

In practice, we can use the heap or priority queue class supplied by the programming language.

Much as a sort can be set to ascending or descending order, we can switch between a min-heap and a max-heap by setting a flag or changing the Comparator, as shown below.

heap.py
# Initialize a min-heap
min_heap, flag = [], 1
# Initialize a max-heap
max_heap, flag = [], -1

# The Python heapq module implements a min-heap by default
# Negate each element before pushing it to reverse the ordering and implement a max-heap
# In this example, flag = 1 selects a min-heap and flag = -1 selects a max-heap

# Push an element onto the heap
heapq.heappush(max_heap, flag * 1)
heapq.heappush(max_heap, flag * 3)
heapq.heappush(max_heap, flag * 2)
heapq.heappush(max_heap, flag * 5)
heapq.heappush(max_heap, flag * 4)

# Get the root element
peek: int = flag * max_heap[0]  # 5

# Pop the root
# The elements come off the heap in descending order
val = flag * heapq.heappop(max_heap)  # 5
val = flag * heapq.heappop(max_heap)  # 4
val = flag * heapq.heappop(max_heap)  # 3
val = flag * heapq.heappop(max_heap)  # 2
val = flag * heapq.heappop(max_heap)  # 1

# Get the heap size
size: int = len(max_heap)

# Check whether the heap is empty
is_empty: bool = not max_heap

# Build a heap from the input list
# The time complexity is O(n), rather than O(nlogn)
min_heap: list[int] = [1, 3, 2, 5, 4]
heapq.heapify(min_heap)
heap.cpp
/* Initialize the heap */
// Initialize a min-heap
priority_queue<int, vector<int>, greater<int>> minHeap;
// Initialize a max-heap
priority_queue<int, vector<int>, less<int>> maxHeap;

/* Push an element onto the heap */
maxHeap.push(1);
maxHeap.push(3);
maxHeap.push(2);
maxHeap.push(5);
maxHeap.push(4);

/* Get the root element */
int peek = maxHeap.top(); // 5

/* Pop the root */
// The elements come off the heap in descending order
maxHeap.pop(); // 5
maxHeap.pop(); // 4
maxHeap.pop(); // 3
maxHeap.pop(); // 2
maxHeap.pop(); // 1

/* Get the heap size */
int size = maxHeap.size();

/* Check whether the heap is empty */
bool isEmpty = maxHeap.empty();

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
vector<int> input{1, 3, 2, 5, 4};
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
heap.java
/* Initialize the heap */
// Initialize a min-heap
Queue<Integer> minHeap = new PriorityQueue<>();
// Initialize a max-heap using a lambda expression to customize the Comparator
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);

/* Push an element onto the heap */
maxHeap.offer(1);
maxHeap.offer(3);
maxHeap.offer(2);
maxHeap.offer(5);
maxHeap.offer(4);

/* Get the root element */
int peek = maxHeap.peek(); // 5

/* Pop the root */
// The elements come off the heap in descending order
peek = maxHeap.poll(); // 5
peek = maxHeap.poll(); // 4
peek = maxHeap.poll(); // 3
peek = maxHeap.poll(); // 2
peek = maxHeap.poll(); // 1

/* Get the heap size */
int size = maxHeap.size();

/* Check whether the heap is empty */
boolean isEmpty = maxHeap.isEmpty();

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
heap.cs
/* Initialize the heap */
// Initialize a min-heap
PriorityQueue<int, int> minHeap = new();
// Initialize a max-heap using a lambda expression to customize the Comparer
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y.CompareTo(x)));

/* Push an element onto the heap */
maxHeap.Enqueue(1, 1);
maxHeap.Enqueue(3, 3);
maxHeap.Enqueue(2, 2);
maxHeap.Enqueue(5, 5);
maxHeap.Enqueue(4, 4);

/* Get the root element */
int peek = maxHeap.Peek(); // 5

/* Pop the root */
// The elements come off the heap in descending order
peek = maxHeap.Dequeue(); // 5
peek = maxHeap.Dequeue(); // 4
peek = maxHeap.Dequeue(); // 3
peek = maxHeap.Dequeue(); // 2
peek = maxHeap.Dequeue(); // 1

/* Get the heap size */
int size = maxHeap.Count;

/* Check whether the heap is empty */
bool isEmpty = maxHeap.Count == 0;

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
heap.go
// In Go, implement heap.Interface to build an integer max-heap
// Implementing heap.Interface also requires implementing sort.Interface
type intHeap []any

// Push implements heap.Interface and adds an element to the heap
func (h *intHeap) Push(x any) {
    // Push and Pop use pointer receivers
    // because they change both the contents of the slice and its length.
    *h = append(*h, x.(int))
}

// Pop implements heap.Interface and removes the last element of the slice (heap.Pop has already moved the root there)
func (h *intHeap) Pop() any {
    // The element to pop is at the end
    last := (*h)[len(*h)-1]
    *h = (*h)[:len(*h)-1]
    return last
}

// Len implements sort.Interface
func (h *intHeap) Len() int {
    return len(*h)
}

// Less implements sort.Interface
func (h *intHeap) Less(i, j int) bool {
    // Use the less-than operator for a min-heap
    return (*h)[i].(int) > (*h)[j].(int)
}

// Swap implements sort.Interface
func (h *intHeap) Swap(i, j int) {
    (*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}

// Top returns the root element
func (h *intHeap) Top() any {
    return (*h)[0]
}

func TestHeap(t *testing.T) {
    /* Initialize the heap */
    // Initialize a max-heap
    maxHeap := &intHeap{}
    heap.Init(maxHeap)
    /* Push an element onto the heap */
    // Call the heap.Interface function to add an element
    heap.Push(maxHeap, 1)
    heap.Push(maxHeap, 3)
    heap.Push(maxHeap, 2)
    heap.Push(maxHeap, 5)
    heap.Push(maxHeap, 4)

    /* Get the root element */
    top := maxHeap.Top()
    fmt.Printf("Root element: %d\n", top)

    /* Pop the root */
    // Call the heap.Interface function to remove an element
    fmt.Printf("Popped element: %d\n", heap.Pop(maxHeap)) // 5
    fmt.Printf("Popped element: %d\n", heap.Pop(maxHeap)) // 4
    fmt.Printf("Popped element: %d\n", heap.Pop(maxHeap)) // 3
    fmt.Printf("Popped element: %d\n", heap.Pop(maxHeap)) // 2
    fmt.Printf("Popped element: %d\n", heap.Pop(maxHeap)) // 1

    /* Get the heap size */
    size := len(*maxHeap)
    fmt.Printf("Number of elements in the heap: %d\n", size)

    /* Check whether the heap is empty */
    isEmpty := len(*maxHeap) == 0
    fmt.Printf("Is the heap empty? %t\n", isEmpty)
}
heap.swift
import HeapModule

/* Initialize the heap */
// Swift's Heap type supports both max-heaps and min-heaps and requires the swift-collections package
var heap = Heap<Int>()

/* Push an element onto the heap */
heap.insert(1)
heap.insert(3)
heap.insert(2)
heap.insert(5)
heap.insert(4)

/* Get the root element */
var peek = heap.max()

/* Pop the root */
peek = heap.removeMax() // 5
peek = heap.removeMax() // 4
peek = heap.removeMax() // 3
peek = heap.removeMax() // 2
peek = heap.removeMax() // 1

/* Get the heap size */
let size = heap.count

/* Check whether the heap is empty */
let isEmpty = heap.isEmpty

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
let heap2 = Heap([1, 3, 2, 5, 4])
heap.js
// JavaScript has no built-in Heap class
heap.ts
// TypeScript has no built-in Heap class
heap.dart
// Dart has no built-in Heap class
heap.rs
use std::{cmp::Reverse, collections::BinaryHeap};

/* Initialize the heap */
// Initialize a min-heap
// Rust's BinaryHeap is a max-heap. Wrap the elements in Reverse for a min-heap
#[allow(unused_assignments)]
let mut min_heap = BinaryHeap::new();
// Initialize a max-heap
let mut max_heap = BinaryHeap::new();

/* Push an element onto the heap */
max_heap.push(1);
max_heap.push(3);
max_heap.push(2);
max_heap.push(5);
max_heap.push(4);

/* Get the root element */
let peek = max_heap.peek().unwrap(); // 5

/* Pop the root */
// The elements come off the heap in descending order
let peek = max_heap.pop().unwrap(); // 5
let peek = max_heap.pop().unwrap(); // 4
let peek = max_heap.pop().unwrap(); // 3
let peek = max_heap.pop().unwrap(); // 2
let peek = max_heap.pop().unwrap(); // 1

/* Get the heap size */
let size = max_heap.len();

/* Check whether the heap is empty */
let is_empty = max_heap.is_empty();

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]);
heap.c
// C has no built-in Heap class
heap.kt
/* Initialize the heap */
// Initialize a min-heap
var minHeap = PriorityQueue<Int>()
// Initialize a max-heap using a lambda expression to customize the Comparator
val maxHeap = PriorityQueue { a: Int, b: Int -> b - a }

/* Push an element onto the heap */
maxHeap.offer(1)
maxHeap.offer(3)
maxHeap.offer(2)
maxHeap.offer(5)
maxHeap.offer(4)

/* Get the root element */
var peek = maxHeap.peek() // 5

/* Pop the root */
// The elements come off the heap in descending order
peek = maxHeap.poll() // 5
peek = maxHeap.poll() // 4
peek = maxHeap.poll() // 3
peek = maxHeap.poll() // 2
peek = maxHeap.poll() // 1

/* Get the heap size */
val size = maxHeap.size

/* Check whether the heap is empty */
val isEmpty = maxHeap.isEmpty()

/* Build a heap from the input list */
// The time complexity is O(n), rather than O(nlogn)
minHeap = PriorityQueue(mutableListOf<Int?>(1, 3, 2, 5, 4))
heap.rb
# Ruby has no built-in Heap class
Visualize execution

8.1.2   Implementing a heap

We implement a max-heap below. To turn it into a min-heap, reverse all value comparisons, for example by replacing \(\geq\) with \(\leq\). Try implementing this version yourself.

1.   Heap storage and representation

As we saw in the chapter on binary trees, arrays are well suited to complete binary trees. A heap is a complete binary tree, so we will store it in an array.

In an array representation of a binary tree, each element holds a node value, and its index gives the node's position in the tree. Index formulas take the place of node pointers.

As the figure shows, for a node at index \(i\), the left child is at \(2i + 1\), the right child is at \(2i + 2\), and the parent is at \((i - 1) / 2\) (using floor division). An out-of-bounds index indicates an empty position or a missing node.

Figure 8-2   Heap representation and storage

Description of Figure 8-2: Array representation of a heap

The same heap can be drawn as a complete binary tree or stored in level order in an array. Index formulas connect the two representations.

The label above the left diagram reads “Logical structure of a heap (a heap is a complete binary tree).” The right reads “Physical structure of a heap (underlying storage: a complete binary tree represented by an array).” The horizontal array on the right holds 12 elements in level order, [9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2], with indices increasing from 0 to 11 from left to right.

In the tree on the left, each circle has its array index below it. The root, 9 at index 0, has left child 8 at index 1 and right child 6 at index 2. The node at index 1 has children at indices 3 (value 6) and 4 (value 7). The node at index 2 has children at indices 5 (value 5) and 6 (value 2). The node at index 3 has children at indices 7 (value 1) and 8 (value 4). The node at index 4 has children at indices 9 (value 3) and 10 (value 6). In each pair, the left child comes first. The node at index 5 has only a left child, at index 11 (value 2).

The array illustrates how index formulas stand in for node pointers. Given index i, a non-root node's parent is at ⌊(i−1)/2⌋ (floor division), its left child at 2i+1, and its right child at 2i+2. Index i=4 (value 7) is highlighted in teal. A gray arrow points to its orange parent at ⌊(4−1)/2⌋ = 1 (value 8). Two arrows lead right from index 4 to its blue left child at 2×4+1 = 9 (value 3) and its blue-violet right child at 2×4+2 = 10 (value 6). Matching colors identify the same nodes in the tree and array.

If a calculated child index is outside the array, that child does not exist. The root at index 0 has no parent. Compact level-order storage gives each node a unique index, so even nodes with equal values, such as the repeated 6s and 2s, can be distinguished.

The compact array representation of a complete binary tree needs no extra parent or child pointer fields. It takes O(1) time to compute the parent and child positions and check whether they exist.

We can put the index formulas in functions for later use.

my_heap.py
def left(self, i: int) -> int:
    """Get the left child index"""
    return 2 * i + 1

def right(self, i: int) -> int:
    """Get the right child index"""
    return 2 * i + 2

def parent(self, i: int) -> int:
    """Get the parent index"""
    return (i - 1) // 2  # Floor division
my_heap.cpp
/* Get the left child index */
int left(int i) {
    return 2 * i + 1;
}

/* Get the right child index */
int right(int i) {
    return 2 * i + 2;
}

/* Get the parent index */
int parent(int i) {
    return (i - 1) / 2; // Floor division
}
my_heap.java
/* Get the left child index */
int left(int i) {
    return 2 * i + 1;
}

/* Get the right child index */
int right(int i) {
    return 2 * i + 2;
}

/* Get the parent index */
int parent(int i) {
    return (i - 1) / 2; // Floor division
}
my_heap.cs
/* Get the left child index */
int Left(int i) {
    return 2 * i + 1;
}

/* Get the right child index */
int Right(int i) {
    return 2 * i + 2;
}

/* Get the parent index */
int Parent(int i) {
    return (i - 1) / 2; // Floor division
}
my_heap.go
/* Get the left child index */
func (h *maxHeap) left(i int) int {
    return 2*i + 1
}

/* Get the right child index */
func (h *maxHeap) right(i int) int {
    return 2*i + 2
}

/* Get the parent index */
func (h *maxHeap) parent(i int) int {
    // Floor division
    return (i - 1) / 2
}
my_heap.swift
/* Get the left child index */
func left(i: Int) -> Int {
    2 * i + 1
}

/* Get the right child index */
func right(i: Int) -> Int {
    2 * i + 2
}

/* Get the parent index */
func parent(i: Int) -> Int {
    (i - 1) / 2 // Floor division
}
my_heap.js
/* Get the left child index */
#left(i) {
    return 2 * i + 1;
}

/* Get the right child index */
#right(i) {
    return 2 * i + 2;
}

/* Get the parent index */
#parent(i) {
    return Math.floor((i - 1) / 2); // Floor division
}
my_heap.ts
/* Get the left child index */
left(i: number): number {
    return 2 * i + 1;
}

/* Get the right child index */
right(i: number): number {
    return 2 * i + 2;
}

/* Get the parent index */
parent(i: number): number {
    return Math.floor((i - 1) / 2); // Floor division
}
my_heap.dart
/* Get the left child index */
int _left(int i) {
  return 2 * i + 1;
}

/* Get the right child index */
int _right(int i) {
  return 2 * i + 2;
}

/* Get the parent index */
int _parent(int i) {
  return (i - 1) ~/ 2; // Floor division
}
my_heap.rs
/* Get the left child index */
fn left(i: usize) -> usize {
    2 * i + 1
}

/* Get the right child index */
fn right(i: usize) -> usize {
    2 * i + 2
}

/* Get the parent index */
fn parent(i: usize) -> usize {
    (i - 1) / 2 // Floor division
}
my_heap.c
/* Get the left child index */
int left(MaxHeap *maxHeap, int i) {
    return 2 * i + 1;
}

/* Get the right child index */
int right(MaxHeap *maxHeap, int i) {
    return 2 * i + 2;
}

/* Get the parent index */
int parent(MaxHeap *maxHeap, int i) {
    return (i - 1) / 2; // Round down
}
my_heap.kt
/* Get the left child index */
fun left(i: Int): Int {
    return 2 * i + 1
}

/* Get the right child index */
fun right(i: Int): Int {
    return 2 * i + 2
}

/* Get the parent index */
fun parent(i: Int): Int {
    return (i - 1) / 2 // Floor division
}
my_heap.rb
### Get the left child index ###
def left(i)
  2 * i + 1
end

### Get the right child index ###
def right(i)
  2 * i + 2
end

### Get the parent index ###
def parent(i)
  (i - 1) / 2     # Floor division
end

2.   Peek at the root

The root element of the heap is the root of the binary tree and the first element of the list.

my_heap.py
def peek(self) -> int:
    """Peek at the root"""
    return self.max_heap[0]
my_heap.cpp
/* Peek at the root */
int peek() {
    return maxHeap[0];
}
my_heap.java
/* Peek at the root */
int peek() {
    return maxHeap.get(0);
}
my_heap.cs
/* Peek at the root */
int Peek() {
    return maxHeap[0];
}
my_heap.go
/* Peek at the root */
func (h *maxHeap) peek() any {
    return h.data[0]
}
my_heap.swift
/* Peek at the root */
func peek() -> Int {
    maxHeap[0]
}
my_heap.js
/* Peek at the root */
peek() {
    return this.#maxHeap[0];
}
my_heap.ts
/* Peek at the root */
peek(): number {
    return this.maxHeap[0];
}
my_heap.dart
/* Peek at the root */
int peek() {
  return _maxHeap[0];
}
my_heap.rs
/* Peek at the root */
fn peek(&self) -> Option<i32> {
    self.max_heap.first().copied()
}
my_heap.c
/* Peek at the root */
int peek(MaxHeap *maxHeap) {
    return maxHeap->data[0];
}
my_heap.kt
/* Peek at the root */
fun peek(): Int {
    return maxHeap[0]
}
my_heap.rb
### Peek at the root ###
def peek
  @max_heap[0]
end
Visualize execution

3.   Push an element onto the heap

To insert val, first append it to the end of the heap. Since val may be larger than other elements, the heap property may no longer hold. We need to repair the nodes along the path from the inserted node to the root. Restoring the heap property is called heapifying.

Starting at the inserted node, sift up from the bottom. As shown below, compare the inserted node with its parent. If the inserted node is larger, swap them. Repeat up the tree until there is no parent left to check or no swap is needed.

Figure 8-3   Steps for pushing an element onto a heap

Description of Figure 8-3: Inserting an element into a max-heap

Append the new element, then compare and swap it with successive parents to restore the max-heap.

The example starts with 12 elements and a root value of 9 at index 0. The new element is 7. Another 7, already at index 4, stays there throughout. The role column in each table distinguishes the two.

The tree and array show the same storage. The array stores nodes in level order, from top to bottom and left to right within each level, starting at index 0. For a non-root position i, the parent index is (i−1)/2 rounded down. The child indices are 2i+1 and 2i+2. An out-of-bounds index means that child is absent. Indices distinguish nodes with equal values.

First append the new element to the level-order array to preserve the complete binary tree shape. Then sift upward along the parent path. Swap only when the current value is greater than its parent. Stop as soon as it is no greater than its parent or reaches the root. In this example, the new 7 rises along indices 12 → 5 → 2 in two swaps.

Each storage table is titled by operation and step. A new table appears only when the array changes. Steps that only compare, stop, or clear highlighting refer by full title to the table with the same contents. Each step still gives the current size, root, and operation.

  1. Prepare to insert a new 7

    There are 12 entries, with 9 at the root. The new 7 is still outside the heap. The original 7 at index 4 is the right child of the 8 at index 1. The two 7s are distinct elements.

    Push, step 1: initial array of 12 elements
    Array indexValueRole in this operation
    09—
    18—
    26—
    36—
    47Original 7
    55—
    62—
    71—
    84—
    93—
    106—
    112—
  2. Append 7 to the end

    There are now 13 entries, with 9 at the root. Append the new 7 at index 12 as the right child of the 5 at index 5. The tree is still complete, but 7 exceeds its parent, 5, and must sift up.

    Push, step 2: array of 13 elements after appending the new 7
    Array indexValueRole in this operation
    09—
    18—
    26—
    36—
    47Original 7
    55—
    62—
    71—
    84—
    93—
    106—
    112—
    127Newly inserted 7
  3. Compare indices 12 and 5

    There are 13 entries, with 9 at the root. Compare the new 7 at index 12 with its parent, 5 at index 5. Since 7 > 5, they need to swap. This step only compares them. For the unchanged array, see “Push, step 2: array of 13 elements after appending the new 7.”

  4. Swap indices 12 and 5

    There are 13 entries, with 9 at the root. For the first upward swap, exchange the new 7 at index 12 with 5 at index 5. The new 7 rises to index 5, and the displaced 5 moves to index 12. The original 7 remains at index 4.

    Push, step 4: array after the first upward swap
    Array indexValueRole in this operation
    09—
    18—
    26—
    36—
    47Original 7
    57Newly inserted 7
    62—
    71—
    84—
    93—
    106—
    112—
    125—
  5. Compare indices 5 and 2

    There are 13 entries, with 9 at the root. Compare the new 7 at index 5 with its parent, 6 at index 2. Since 7 > 6, it must continue upward. No swap has occurred in this step. For the unchanged array, see “Push, step 4: array after the first upward swap.”

  6. Swap indices 5 and 2

    There are 13 entries, with 9 at the root. For the second upward swap, exchange the new 7 at index 5 with 6 at index 2. The new 7 rises to index 2, and the displaced 6 moves down to index 5. Next, check the root.

    Push, step 6: array after the second upward swap
    Array indexValueRole in this operation
    09—
    18—
    27Newly inserted 7
    36—
    47Original 7
    56—
    62—
    71—
    84—
    93—
    106—
    112—
    125—
  7. Compare index 2 with the root

    There are 13 entries, with 9 at the root. Compare the new 7 at index 2 with its parent, the 9 at root index 0. Since 9 > 7, the parent is at least as large as its child, and no swap is needed. For the unchanged array, see “Push, step 6: array after the second upward swap.”

  8. Stop sifting up

    There are 13 entries, with 9 at the root. The new 7 stops at index 2 because the root, 9, is larger. No further swap occurs. For the unchanged array, see “Push, step 6: array after the second upward swap.”

  9. Insertion complete

    There are 13 entries, with 9 at the root. Clear the comparison highlights to finish the insertion. The new 7 is at index 2, the original 7 is at index 4, and the displaced 5 is at the last index, 12. All 13 entries satisfy the max-heap property again. For the unchanged array, see “Push, step 6: array after the second upward swap.”

The new 7 rises along indices 12→5→2 in two swaps. The original 7 stays at index 4 throughout.

With \(n\) nodes, the tree has height \(O(\log n)\). Sifting therefore takes at most \(O(\log n)\) iterations, and pushing an element onto a heap takes \(O(\log n)\) time. The code follows.

my_heap.py
def push(self, val: int):
    """Push an element onto the heap"""
    # Add a node
    self.max_heap.append(val)
    # Sift up
    self.sift_up(self.size() - 1)

def sift_up(self, i: int):
    """Sift up from node i"""
    while True:
        # Get the parent of node i
        p = self.parent(i)
        # Stop sifting at the root or when the node already satisfies the heap property
        if p < 0 or self.max_heap[i] <= self.max_heap[p]:
            break
        # Swap the two nodes
        self.swap(i, p)
        # Continue sifting up
        i = p
my_heap.cpp
/* Push an element onto the heap */
void push(int val) {
    // Add a node
    maxHeap.push_back(val);
    // Sift up
    siftUp(size() - 1);
}

/* Sift up from node i */
void siftUp(int i) {
    while (true) {
        // Get the parent of node i
        int p = parent(i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || maxHeap[i] <= maxHeap[p])
            break;
        // Swap the two nodes
        swap(maxHeap[i], maxHeap[p]);
        // Continue sifting up
        i = p;
    }
}
my_heap.java
/* Push an element onto the heap */
void push(int val) {
    // Add a node
    maxHeap.add(val);
    // Sift up
    siftUp(size() - 1);
}

/* Sift up from node i */
void siftUp(int i) {
    while (true) {
        // Get the parent of node i
        int p = parent(i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
            break;
        // Swap the two nodes
        swap(i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.cs
/* Push an element onto the heap */
void Push(int val) {
    // Add a node
    maxHeap.Add(val);
    // Sift up
    SiftUp(Size() - 1);
}

/* Sift up from node i */
void SiftUp(int i) {
    while (true) {
        // Get the parent of node i
        int p = Parent(i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || maxHeap[i] <= maxHeap[p])
            break;
        // Swap the two nodes
        Swap(i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.go
/* Push an element onto the heap */
func (h *maxHeap) push(val any) {
    // Add a node
    h.data = append(h.data, val)
    // Sift up
    h.siftUp(len(h.data) - 1)
}

/* Sift up from node i */
func (h *maxHeap) siftUp(i int) {
    for true {
        // Get the parent of node i
        p := h.parent(i)
        // Stop sifting at the root or when the node already satisfies the heap property
        if p < 0 || h.data[i].(int) <= h.data[p].(int) {
            break
        }
        // Swap the two nodes
        h.swap(i, p)
        // Continue sifting up
        i = p
    }
}
my_heap.swift
/* Push an element onto the heap */
func push(val: Int) {
    // Add a node
    maxHeap.append(val)
    // Sift up
    siftUp(i: size() - 1)
}

/* Sift up from node i */
func siftUp(i: Int) {
    var i = i
    while true {
        // Get the parent of node i
        let p = parent(i: i)
        // Stop sifting at the root or when the node already satisfies the heap property
        if p < 0 || maxHeap[i] <= maxHeap[p] {
            break
        }
        // Swap the two nodes
        swap(i: i, j: p)
        // Continue sifting up
        i = p
    }
}
my_heap.js
/* Push an element onto the heap */
push(val) {
    // Add a node
    this.#maxHeap.push(val);
    // Sift up
    this.#siftUp(this.size() - 1);
}

/* Sift up from node i */
#siftUp(i) {
    while (true) {
        // Get the parent of node i
        const p = this.#parent(i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
        // Swap the two nodes
        this.#swap(i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.ts
/* Push an element onto the heap */
push(val: number): void {
    // Add a node
    this.maxHeap.push(val);
    // Sift up
    this.siftUp(this.size() - 1);
}

/* Sift up from node i */
siftUp(i: number): void {
    while (true) {
        // Get the parent of node i
        const p = this.parent(i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || this.maxHeap[i] <= this.maxHeap[p]) break;
        // Swap the two nodes
        this.swap(i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.dart
/* Push an element onto the heap */
void push(int val) {
  // Add a node
  _maxHeap.add(val);
  // Sift up
  siftUp(size() - 1);
}

/* Sift up from node i */
void siftUp(int i) {
  while (true) {
    // Get the parent of node i
    int p = _parent(i);
    // Stop sifting at the root or when the node already satisfies the heap property
    if (p < 0 || _maxHeap[i] <= _maxHeap[p]) {
      break;
    }
    // Swap the two nodes
    _swap(i, p);
    // Continue sifting up
    i = p;
  }
}
my_heap.rs
/* Push an element onto the heap */
fn push(&mut self, val: i32) {
    // Add a node
    self.max_heap.push(val);
    // Sift up
    self.sift_up(self.size() - 1);
}

/* Sift up from node i */
fn sift_up(&mut self, mut i: usize) {
    loop {
        // Node i is already the root, so stop sifting
        if i == 0 {
            break;
        }
        // Get the parent of node i
        let p = Self::parent(i);
        // Stop sifting when the node already satisfies the heap property
        if self.max_heap[i] <= self.max_heap[p] {
            break;
        }
        // Swap the two nodes
        self.swap(i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.c
/* Push an element onto the heap */
void push(MaxHeap *maxHeap, int val) {
    // The default capacity should be enough for the expected number of nodes
    if (maxHeap->size == MAX_SIZE) {
        printf("heap is full!");
        return;
    }
    // Add a node
    maxHeap->data[maxHeap->size] = val;
    maxHeap->size++;

    // Sift up
    siftUp(maxHeap, maxHeap->size - 1);
}

/* Sift up from node i */
void siftUp(MaxHeap *maxHeap, int i) {
    while (true) {
        // Get the parent of node i
        int p = parent(maxHeap, i);
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || maxHeap->data[i] <= maxHeap->data[p]) {
            break;
        }
        // Swap the two nodes
        swap(maxHeap, i, p);
        // Continue sifting up
        i = p;
    }
}
my_heap.kt
/* Push an element onto the heap */
fun push(_val: Int) {
    // Add a node
    maxHeap.add(_val)
    // Sift up
    siftUp(size() - 1)
}

/* Sift up from node i */
fun siftUp(it: Int) {
    // Kotlin function parameters are read-only, so create a temporary variable
    var i = it
    while (true) {
        // Get the parent of node i
        val p = parent(i)
        // Stop sifting at the root or when the node already satisfies the heap property
        if (p < 0 || maxHeap[i] <= maxHeap[p]) break
        // Swap the two nodes
        swap(i, p)
        // Continue sifting up
        i = p
    }
}
my_heap.rb
### Push an element onto the heap ###
def push(val)
  # Add a node
  @max_heap << val
  # Sift up
  sift_up(size - 1)
end

### Sift up from node i ###
def sift_up(i)
  loop do
    # Get the parent of node i
    p = parent(i)
    # Stop sifting at the root or when the node already satisfies the heap property
    break if p < 0 || @max_heap[i] <= @max_heap[p]
    # Swap the two nodes
    swap(i, p)
    # Continue sifting up
    i = p
  end
end
Visualize execution

4.   Pop the root

The heap root is the root of the binary tree and the first element of the list. Removing the first element directly would change every remaining node's index and make the heap hard to repair. To minimize index changes, use the following steps.

  1. Swap the root with the last element (the rightmost leaf).
  2. Remove the last element from the list. After the swap, this is the original root.
  3. Starting at the root, sift down toward the leaves.

As Figure 8-4 shows, sifting down moves in the opposite direction from sifting up. Compare the root with its children and swap with the larger child if necessary. Repeat at the new position until there are no more children or no swap is needed.

Figure 8-4   Steps for popping the root of a heap

Description of Figure 8-4: Popping the root of a max-heap

After removing the maximum, restore the max-heap by sifting down from the root, swapping with the larger child.

The example starts with 13 elements. The maximum, 9, is at root index 0, and the last element, at index 12, is 5. In a max-heap, each parent's value must be at least as large as each child's.

The tree and array show the same storage. The array stores nodes in level order, from top to bottom and left to right within each level, starting at index 0. For a non-root position i, the parent index is (i−1)/2 rounded down. The child indices are 2i+1 and 2i+2. An out-of-bounds index means that child is absent. Indices distinguish nodes with equal values.

To pop, first swap the root at index 0 with the last element at index 12, then remove the former root from the end. This avoids shifting all subsequent elements as deleting the first entry would. Now sift down from the root. At each step, find the largest value among the current node and its children. If a child is larger, swap with the larger child. Only this choice guarantees that the new parent is at least as large as the other child. Stop when the current node is at least as large as its children or reaches a leaf.

Each storage table is titled by operation and step. A new table appears only when the array changes. Steps that only compare, stop, or clear highlighting refer by full title to the table with the same contents. Each step still gives the current size, root, and operation.

  1. Locate the root, 9, and the last element, 5

    There are 13 entries, with 9 at the root. The 9 to be popped is at root index 0. The 5 at the last index, 12, will take its place. Nothing has been swapped or removed yet.

    Pop, step 1: initial array of 13 elements
    Array indexValueRole in this operation
    099 to be popped
    18—
    27—
    36—
    47—
    56—
    62—
    71—
    84—
    93—
    106—
    112—
    1255 being sifted down
  2. Swap the first and last elements

    There are 13 entries, with 5 at the root. Swap the 9 at index 0 with the 5 at index 12. The root becomes 5, and 9 moves to the end. All 13 entries remain because 9 has not yet been removed.

    Pop, step 2: array of 13 elements after swapping the first and last
    Array indexValueRole in this operation
    055 being sifted down
    18—
    27—
    36—
    47—
    56—
    62—
    71—
    84—
    93—
    106—
    112—
    1299 to be popped
  3. Remove 9 from the end

    There are now 12 entries, with 5 at the root. Remove 9 from the end, formerly index 12, and save it as the return value. Removing the rightmost leaf preserves the shape of the complete binary tree, but the 5 at root index 0 is smaller than its children and must sift down.

    Pop, step 3: array of 12 elements after removing the final 9
    Array indexValueRole in this operation
    055 being sifted down
    18—
    27—
    36—
    47—
    56—
    62—
    71—
    84—
    93—
    106—
    112—
  4. Compare root 5 with its children

    There are 12 entries, with 5 at the root. Compare 5 at index 0 with its left child, 8 at index 1, and its right child, 7 at index 2. The largest is 8 at index 1. It will be swapped in the next step. This step only compares values. For the unchanged array, see “Pop, step 3: array of 12 elements after removing the final 9.”

  5. Swap indices 0 and 1

    There are 12 entries, with 8 at the root. For the first downward swap, exchange 5 at index 0 with 8 at index 1. The new root, 8, exceeds its right child, 7 at index 2. The 5 moves to index 1, with left child 6 at index 3 and right child 7 at index 4.

    Pop, step 5: array after the first downward swap
    Array indexValueRole in this operation
    08—
    155 being sifted down
    27—
    36—
    47—
    56—
    62—
    71—
    84—
    93—
    106—
    112—
  6. Compare the children of index 1

    There are 12 entries, with 8 at the root. Compare 5 at index 1 with its left child, 6 at index 3, and its right child, 7 at index 4. The largest is 7 at index 4. No swap has occurred yet. The other 7, at index 2 to the right of the root, is outside this comparison. For the unchanged array, see “Pop, step 5: array after the first downward swap.”

  7. Swap indices 1 and 4

    There are 12 entries, with 8 at the root. For the second downward swap, exchange 5 at index 1 with 7 at index 4. The 7 rises to index 1, and 5 sinks to index 4. Its left and right children are now 3 at index 9 and 6 at index 10.

    Pop, step 7: array after the second downward swap
    Array indexValueRole in this operation
    08—
    17—
    27—
    36—
    455 being sifted down
    56—
    62—
    71—
    84—
    93—
    106—
    112—
  8. Compare the children of index 4

    There are 12 entries, with 8 at the root. Compare 5 at index 4 with its left child, 3 at index 9, and its right child, 6 at index 10. The largest is 6 at index 10, so sifting must continue. No swap has occurred in this step. For the unchanged array, see “Pop, step 7: array after the second downward swap.”

  9. Swap indices 4 and 10

    There are 12 entries, with 8 at the root. For the third downward swap, exchange 5 at index 4 with 6 at index 10. The 6 rises to index 4, and 5 reaches a leaf at index 10. Its child indices 21 and 22 are both out of bounds, so sifting stops.

    Pop, step 9: array after the third downward swap
    Array indexValueRole in this operation
    08—
    17—
    27—
    36—
    46—
    56—
    62—
    71—
    84—
    93—
    1055 being sifted down
    112—
  10. Pop complete

    There are 12 entries, with 8 at the root. Clear the highlighting and complete the pop by returning the 9 removed earlier. The 5 finishes at index 10, and all 12 entries again satisfy the max-heap property. For the unchanged array, see “Pop, step 9: array after the third downward swap.”

The pop returns 9. The value 5 sinks along indices 0→1→4→10 in three swaps.

As with insertion, popping the root takes \(O(\log n)\) time. The code follows.

my_heap.py
def pop(self) -> int:
    """Pop an element from the heap"""
    # Handle an empty heap
    if self.is_empty():
        raise IndexError("Heap is empty")
    # Swap the root and the rightmost leaf (the first and last elements)
    self.swap(0, self.size() - 1)
    # Remove the node
    val = self.max_heap.pop()
    # Sift down
    self.sift_down(0)
    # Return the root element
    return val

def sift_down(self, i: int):
    """Sift down from node i"""
    while True:
        # Store the index of the largest of nodes i, l, and r in ma
        l, r, ma = self.left(i), self.right(i), i
        if l < self.size() and self.max_heap[l] > self.max_heap[ma]:
            ma = l
        if r < self.size() and self.max_heap[r] > self.max_heap[ma]:
            ma = r
        # Stop if i is already largest or both child indices l and r are out of bounds
        if ma == i:
            break
        # Swap the two nodes
        self.swap(i, ma)
        # Continue sifting down
        i = ma
my_heap.cpp
/* Pop an element from the heap */
void pop() {
    // Handle an empty heap
    if (isEmpty()) {
        throw out_of_range("Heap is empty");
    }
    // Swap the root and the rightmost leaf (the first and last elements)
    swap(maxHeap[0], maxHeap[size() - 1]);
    // Remove the node
    maxHeap.pop_back();
    // Sift down
    siftDown(0);
}

/* Sift down from node i */
void siftDown(int i) {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        int l = left(i), r = right(i), ma = i;
        if (l < size() && maxHeap[l] > maxHeap[ma])
            ma = l;
        if (r < size() && maxHeap[r] > maxHeap[ma])
            ma = r;
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (ma == i)
            break;
        swap(maxHeap[i], maxHeap[ma]);
        // Continue sifting down
        i = ma;
    }
}
my_heap.java
/* Pop an element from the heap */
int pop() {
    // Handle an empty heap
    if (isEmpty())
        throw new IndexOutOfBoundsException();
    // Swap the root and the rightmost leaf (the first and last elements)
    swap(0, size() - 1);
    // Remove the node
    int val = maxHeap.remove(size() - 1);
    // Sift down
    siftDown(0);
    // Return the root element
    return val;
}

/* Sift down from node i */
void siftDown(int i) {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        int l = left(i), r = right(i), ma = i;
        if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
            ma = l;
        if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
            ma = r;
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (ma == i)
            break;
        // Swap the two nodes
        swap(i, ma);
        // Continue sifting down
        i = ma;
    }
}
my_heap.cs
/* Pop an element from the heap */
int Pop() {
    // Handle an empty heap
    if (IsEmpty())
        throw new IndexOutOfRangeException();
    // Swap the root and the rightmost leaf (the first and last elements)
    Swap(0, Size() - 1);
    // Remove the node
    int val = maxHeap.Last();
    maxHeap.RemoveAt(Size() - 1);
    // Sift down
    SiftDown(0);
    // Return the root element
    return val;
}

/* Sift down from node i */
void SiftDown(int i) {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        int l = Left(i), r = Right(i), ma = i;
        if (l < Size() && maxHeap[l] > maxHeap[ma])
            ma = l;
        if (r < Size() && maxHeap[r] > maxHeap[ma])
            ma = r;
        // Stop sifting if node i is largest or there are no children below it
        if (ma == i) break;
        // Swap the two nodes
        Swap(i, ma);
        // Continue sifting down
        i = ma;
    }
}
my_heap.go
/* Pop an element from the heap */
func (h *maxHeap) pop() any {
    // Handle an empty heap
    if h.isEmpty() {
        fmt.Println("error")
        return nil
    }
    // Swap the root and the rightmost leaf (the first and last elements)
    h.swap(0, h.size()-1)
    // Remove the node
    val := h.data[len(h.data)-1]
    h.data = h.data[:len(h.data)-1]
    // Sift down
    h.siftDown(0)

    // Return the root element
    return val
}

/* Sift down from node i */
func (h *maxHeap) siftDown(i int) {
    for true {
        // Store the index of the largest of nodes i, l, and r in max
        l, r, max := h.left(i), h.right(i), i
        if l < h.size() && h.data[l].(int) > h.data[max].(int) {
            max = l
        }
        if r < h.size() && h.data[r].(int) > h.data[max].(int) {
            max = r
        }
        // Stop if i is already largest or both child indices l and r are out of bounds
        if max == i {
            break
        }
        // Swap the two nodes
        h.swap(i, max)
        // Continue sifting down
        i = max
    }
}
my_heap.swift
/* Pop an element from the heap */
func pop() -> Int {
    // Handle an empty heap
    if isEmpty() {
        fatalError("Heap is empty")
    }
    // Swap the root and the rightmost leaf (the first and last elements)
    swap(i: 0, j: size() - 1)
    // Remove the node
    let val = maxHeap.remove(at: size() - 1)
    // Sift down
    siftDown(i: 0)
    // Return the root element
    return val
}

/* Sift down from node i */
func siftDown(i: Int) {
    var i = i
    while true {
        // Store the index of the largest of nodes i, l, and r in ma
        let l = left(i: i)
        let r = right(i: i)
        var ma = i
        if l < size(), maxHeap[l] > maxHeap[ma] {
            ma = l
        }
        if r < size(), maxHeap[r] > maxHeap[ma] {
            ma = r
        }
        // Stop if i is already largest or both child indices l and r are out of bounds
        if ma == i {
            break
        }
        // Swap the two nodes
        swap(i: i, j: ma)
        // Continue sifting down
        i = ma
    }
}
my_heap.js
/* Pop an element from the heap */
pop() {
    // Handle an empty heap
    if (this.isEmpty()) throw new Error('Heap is empty');
    // Swap the root and the rightmost leaf (the first and last elements)
    this.#swap(0, this.size() - 1);
    // Remove the node
    const val = this.#maxHeap.pop();
    // Sift down
    this.#siftDown(0);
    // Return the root element
    return val;
}

/* Sift down from node i */
#siftDown(i) {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        const l = this.#left(i),
            r = this.#right(i);
        let ma = i;
        if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;
        if (r < this.size() && this.#maxHeap[r] > this.#maxHeap[ma]) ma = r;
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (ma === i) break;
        // Swap the two nodes
        this.#swap(i, ma);
        // Continue sifting down
        i = ma;
    }
}
my_heap.ts
/* Pop an element from the heap */
pop(): number {
    // Handle an empty heap
    if (this.isEmpty()) throw new RangeError('Heap is empty.');
    // Swap the root and the rightmost leaf (the first and last elements)
    this.swap(0, this.size() - 1);
    // Remove the node
    const val = this.maxHeap.pop();
    // Sift down
    this.siftDown(0);
    // Return the root element
    return val;
}

/* Sift down from node i */
siftDown(i: number): void {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        const l = this.left(i),
            r = this.right(i);
        let ma = i;
        if (l < this.size() && this.maxHeap[l] > this.maxHeap[ma]) ma = l;
        if (r < this.size() && this.maxHeap[r] > this.maxHeap[ma]) ma = r;
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (ma === i) break;
        // Swap the two nodes
        this.swap(i, ma);
        // Continue sifting down
        i = ma;
    }
}
my_heap.dart
/* Pop an element from the heap */
int pop() {
  // Handle an empty heap
  if (isEmpty()) throw Exception('Heap is empty');
  // Swap the root and the rightmost leaf (the first and last elements)
  _swap(0, size() - 1);
  // Remove the node
  int val = _maxHeap.removeLast();
  // Sift down
  siftDown(0);
  // Return the root element
  return val;
}

/* Sift down from node i */
void siftDown(int i) {
  while (true) {
    // Store the index of the largest of nodes i, l, and r in ma
    int l = _left(i);
    int r = _right(i);
    int ma = i;
    if (l < size() && _maxHeap[l] > _maxHeap[ma]) ma = l;
    if (r < size() && _maxHeap[r] > _maxHeap[ma]) ma = r;
    // Stop if i is already largest or both child indices l and r are out of bounds
    if (ma == i) break;
    // Swap the two nodes
    _swap(i, ma);
    // Continue sifting down
    i = ma;
  }
}
my_heap.rs
/* Pop an element from the heap */
fn pop(&mut self) -> i32 {
    // Handle an empty heap
    if self.is_empty() {
        panic!("index out of bounds");
    }
    // Swap the root and the rightmost leaf (the first and last elements)
    self.swap(0, self.size() - 1);
    // Remove the node
    let val = self.max_heap.pop().unwrap();
    // Sift down
    self.sift_down(0);
    // Return the root element
    val
}

/* Sift down from node i */
fn sift_down(&mut self, mut i: usize) {
    loop {
        // Store the index of the largest of nodes i, l, and r in ma
        let (l, r, mut ma) = (Self::left(i), Self::right(i), i);
        if l < self.size() && self.max_heap[l] > self.max_heap[ma] {
            ma = l;
        }
        if r < self.size() && self.max_heap[r] > self.max_heap[ma] {
            ma = r;
        }
        // Stop if i is already largest or both child indices l and r are out of bounds
        if ma == i {
            break;
        }
        // Swap the two nodes
        self.swap(i, ma);
        // Continue sifting down
        i = ma;
    }
}
my_heap.c
/* Pop an element from the heap */
int pop(MaxHeap *maxHeap) {
    // Handle an empty heap
    if (isEmpty(maxHeap)) {
        printf("heap is empty!");
        return INT_MAX;
    }
    // Swap the root and the rightmost leaf (the first and last elements)
    swap(maxHeap, 0, size(maxHeap) - 1);
    // Remove the node
    int val = maxHeap->data[maxHeap->size - 1];
    maxHeap->size--;
    // Sift down
    siftDown(maxHeap, 0);

    // Return the root element
    return val;
}

/* Sift down from node i */
void siftDown(MaxHeap *maxHeap, int i) {
    while (true) {
        // Store the index of the largest of nodes i, l, and r in max
        int l = left(maxHeap, i);
        int r = right(maxHeap, i);
        int max = i;
        if (l < size(maxHeap) && maxHeap->data[l] > maxHeap->data[max]) {
            max = l;
        }
        if (r < size(maxHeap) && maxHeap->data[r] > maxHeap->data[max]) {
            max = r;
        }
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (max == i) {
            break;
        }
        // Swap the two nodes
        swap(maxHeap, i, max);
        // Continue sifting down
        i = max;
    }
}
my_heap.kt
/* Pop an element from the heap */
fun pop(): Int {
    // Handle an empty heap
    if (isEmpty()) throw IndexOutOfBoundsException()
    // Swap the root and the rightmost leaf (the first and last elements)
    swap(0, size() - 1)
    // Remove the node
    val _val = maxHeap.removeAt(size() - 1)
    // Sift down
    siftDown(0)
    // Return the root element
    return _val
}

/* Sift down from node i */
fun siftDown(it: Int) {
    // Kotlin function parameters are read-only, so create a temporary variable
    var i = it
    while (true) {
        // Store the index of the largest of nodes i, l, and r in ma
        val l = left(i)
        val r = right(i)
        var ma = i
        if (l < size() && maxHeap[l] > maxHeap[ma]) ma = l
        if (r < size() && maxHeap[r] > maxHeap[ma]) ma = r
        // Stop if i is already largest or both child indices l and r are out of bounds
        if (ma == i) break
        // Swap the two nodes
        swap(i, ma)
        // Continue sifting down
        i = ma
    }
}
my_heap.rb
### Pop an element from the heap ###
def pop
  # Handle an empty heap
  raise IndexError, "Heap is empty" if is_empty?
  # Swap the root and the rightmost leaf (the first and last elements)
  swap(0, size - 1)
  # Remove the node
  val = @max_heap.pop
  # Sift down
  sift_down(0)
  # Return the root element
  val
end

### Sift down from node i ###
def sift_down(i)
  loop do
    # Store the index of the largest of nodes i, l, and r in ma
    l, r, ma = left(i), right(i), i
    ma = l if l < size && @max_heap[l] > @max_heap[ma]
    ma = r if r < size && @max_heap[r] > @max_heap[ma]

    # Stop if i is already largest or both child indices l and r are out of bounds
    break if ma == i

    # Swap the two nodes
    swap(i, ma)
    # Continue sifting down
    i = ma
  end
end
Visualize execution

8.1.3   Common applications of heaps

  • Priority queues: A heap is usually the first choice for implementing a priority queue. Enqueueing and dequeueing each take \(O(\log n)\) time, and building the heap takes \(O(n)\). All three operations are efficient.
  • Heapsort: Given a collection of values, build a heap and repeatedly pop its root to obtain the values in sorted order. In practice, we usually use a more elegant implementation, described in the section on heapsort.
  • Finding the \(k\) largest elements: This classic algorithm problem also arises in practice, for example when selecting the ten most popular news stories for Weibo's trending list or the ten best-selling products.
Share your thoughts, questions, or suggestions in the comments.