Lably
Skip to content

Binary heap

Variant of heap data structure

  • 15 min read
  • 6 chapters

Related on Lably

Through Data structure, Binary tree and Transitive relation

A binary heap is defined as a binary tree with two additional constraints:

  • Shape property: a binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
  • Heap property: the key stored in each node is either greater than or equal to (≥) (or less than or equal to (≤)) the keys in the node's children, according to some total order.

Heaps where the parent key is greater than or equal to (≥) the child keys are called max-heaps; those where it is less than or equal to (≤) are called min-heaps. Efficient (that is, logarithmic time) algorithms are known for the two operations needed to implement a priority queue on a binary heap:

  • Inserting an element;
  • Removing the smallest or largest element from (respectively) a min-heap or max-heap.

Binary heaps are also commonly employed in the heapsort sorting algorithm, which is an in-place algorithm as binary heaps can be implemented as an implicit data structure, storing keys in an array and using their relative positions within that array to represent child–parent relationships.

Heap operations

Both the insert and remove operations modify the heap to preserve the shape property first, by adding or removing from the end of the heap. Then the heap property is restored by traversing up or down the heap. Both operations take O(log n) time.

Insert

To insert an element to a heap, we perform the following steps:

  1. Add the element to the bottom level of the heap at the leftmost open space.
  2. Compare the added element with its parent; if they are in the correct order, stop.
  3. If not, swap the element with its parent and return to the previous step.

Steps 2 and 3, which restore the heap property by comparing and possibly swapping a node with its parent, are called the up-heap operation (also known as bubble-up, percolate-up, sift-up, trickle-up, swim-up, heapify-up, cascade-up, or fix-up).

The number of operations required depends only on the number of levels the new element must rise to satisfy the heap property. Thus, the insertion operation has a worst-case time complexity of O(log n). For a random heap, and for repeated insertions, the insertion operation has an average-case complexity of O(1).

The following animation depicts an example of binary heap insertion. It begins by inserting 15 into the heap at the left-most empty entry on the next available row. However, the heap property is violated since 15 > 8, so we need to swap the 15 and the 8. Even after this swap, the heap property is still violated since 15 > 11, so we need to swap again. The heap property is now satisfied, so the resulting binary tree is a valid max-heap. There is no need to check the left child after this final step: at the start, the max-heap was valid, meaning the root was already greater than its left child, so replacing the root with an even greater value will maintain the property that each node is greater than its children (11 > 5; if 15 > 11, and 11 > 5, then 15 > 5, because of the transitive relation).

Extract

The procedure for deleting the root from the heap (effectively extracting the maximum element in a max-heap or the minimum element in a min-heap) while retaining the heap property is as follows:

  1. Replace the root of the heap with the last element on the last level.
  2. Compare the new root with its children; if they are in the correct order, stop.
  3. If not, swap the element with one of its children and return to the previous step. (Swap with its smaller child in a min-heap and its larger child in a max-heap.)

Steps 2 and 3, which restore the heap property by comparing and possibly swapping a node with one of its children, are called the down-heap (also known as bubble-down, percolate-down, sift-down, sink-down, trickle down, heapify-down, cascade-down, fix-down, extract-min or extract-max, or simply heapify) operation.

So, if we have the same max-heap as before, we remove the 11 and replace it with the 4. Now the heap property is violated since 8 is greater than 4. In this case, swapping the two elements, 4 and 8, is enough to restore the heap property and we need not swap elements further.

The downward-moving node is swapped with the larger of its children in a max-heap (in a min-heap it would be swapped with its smaller child), until it satisfies the heap property in its new position. This functionality is achieved by the Max-Heapify function as defined below in pseudocode for an array-backed heap A of length length(A). A is indexed starting at 1.

// Perform a down-heap or heapify-down operation for a max-heap // <i id="mwgA">A</i>: an array representing the heap, indexed starting at 1 // <i id="mwgQ">i</i>: the index to start at when heapifying down <b id="mwgg">Max-Heapify</b>(<i id="mwgw">A</i>, <i id="mwhA">i</i>): <i id="mwhQ">left</i> ← 2×<i id="mwhg">i</i> <i id="mwhw">right</i> ← 2×<i id="mwiA">i</i> + 1 <i id="mwiQ">largest</i> ← <i id="mwig">i</i> <b id="mwiw">if</b> <i id="mwjA">left</i> ≤ <i id="mwjQ">length</i>(<i id="mwjg">A</i>) <b id="mwjw">and</b> <i id="mwkA">A</i>[<i id="mwkQ">left</i>] > A[<i id="mwkg">largest</i>] <b id="mwkw">then</b>: <i id="mwlA">largest</i> ← <i id="mwlQ">left</i><br id="mwlg"/> <b id="mwlw">if</b> <i id="mwmA">right</i> ≤ <i id="mwmQ">length</i>(<i id="mwmg">A</i>) <b id="mwmw">and</b> <i id="mwnA">A</i>[<i id="mwnQ">right</i>] > <i id="mwng">A</i>[<i id="mwnw">largest</i>] <b id="mwoA">then</b>: <i id="mwoQ">largest</i> ← <i id="mwog">right</i> <b id="mwow">if</b> <i id="mwpA">largest</i> ≠ <i id="mwpQ">i</i> <b id="mwpg">then</b>: <b id="mwpw">swap</b> <i id="mwqA">A</i>[<i id="mwqQ">i</i>] and <i id="mwqg">A</i>[<i id="mwqw">largest</i>] <b id="mwrA">Max-Heapify</b>(<i id="mwrQ">A</i>, <i id="mwrg">largest</i>)

For the above algorithm to correctly re-heapify the array, no nodes besides the node at index i and its two direct children can violate the heap property. The down-heap operation (without the preceding swap) can also be used to modify the value of the root, even when an element is not being deleted.

In the worst case, the new root has to be swapped with its child on each level until it reaches the bottom level of the heap, meaning that the delete operation has a time complexity relative to the height of the tree, or O(log n).

Insert then extract

Inserting an element then extracting from the heap can be done more efficiently than simply calling the insert and extract functions defined above, which would involve both an upheap and downheap operation. Instead, we can do just a downheap operation, as follows:

  1. Compare whether the item we're pushing or the peeked top of the heap is greater (assuming a max heap)
  2. If the root of the heap is greater:
    1. Replace the root with the new item
    2. Down-heapify starting from the root
  3. Else, return the item we're pushing

Python provides such a function for insertion then extraction called "heappushpop", which is paraphrased below. The heap array is assumed to have its first element at index 1.

// Push a new item to a (max) heap and then extract the root of the resulting heap. // <i id="mwyg">heap</i>: an array representing the heap, indexed at 1 // <i id="mwyw">item</i>: an element to insert // Returns the greater of the two between <i id="mwzA">item</i> and the root of <i id="mwzQ">heap</i>. <b id="mwzg">Push-Pop</b>(<i id="mwzw">heap</i>: List<T>, <i id="mw0A">item</i>: T) -> T: <b id="mw0Q">if</b> <i id="mw0g">heap</i> is not empty <b id="mw0w">and</b> heap[1] > <i id="mw1A">item</i> <b id="mw1Q">then</b>: // < if min heap <b id="mw1g">swap</b> <i id="mw1w">heap</i>[1] and <i id="mw2A">item</i> _downheap(<i id="mw2Q">heap</i> starting from index 1) <b id="mw2g">return</b> <i id="mw2w">item</i>

A similar function can be defined for popping and then inserting, which in Python is called "heapreplace":

// Extract the root of the heap, and push a new item // <i id="mw3g">heap</i>: an array representing the heap, indexed at 1 // <i id="mw3w">item</i>: an element to insert // Returns the current root of <i id="mw4A">heap</i> <b id="mw4Q">Replace</b>(<i id="mw4g">heap</i>: List<T>, <i id="mw4w">item</i>: T) -> T: <b id="mw5A">swap</b> <i id="mw5Q">heap</i>[1] and <i id="mw5g">item</i> _downheap(<i id="mw5w">heap</i> starting from index 1) <b id="mw6A">return</b> <i id="mw6Q">item</i>

Finding an arbitrary element takes O(n) time.

This can be easily proved by considering that the heap is not sorted so we need to look through the whole tree to find the target element.

Delete

Deleting an arbitrary element can be done as follows:

  1. Find the index i of the element we want to delete
  2. Swap this element with the last element. Remove the last element after the swap.
  3. Down-heapify or up-heapify to restore the heap property. In a max-heap (min-heap), up-heapify is only required when the new key of element i is greater (smaller) than the previous one because only the heap-property of the parent element might be violated. Assuming that the heap-property was valid between element i and its children before the element swap, it can't be violated by a now larger (smaller) key value. When the new key is less (greater) than the previous one then only a down-heapify is required because the heap-property might only be violated in the child elements.

Decrease or increase key

The decrease key operation replaces the value of a node with a given value with a lower value, and the increase key operation does the same but with a higher value. This involves finding the node with the given value, changing the value, and then down-heapifying or up-heapifying to restore the heap property.

Decrease key can be done as follows:

  1. Find the index of the element we want to modify
  2. Decrease the value of the node
  3. Down-heapify (assuming a max heap) to restore the heap property

Increase key can be done as follows:

  1. Find the index of the element we want to modify
  2. Increase the value of the node
  3. Up-heapify (assuming a max heap) to restore the heap property

Sign in to keep reading

5 more chapters are free with a Lably account.

More in Computing and communication