ArticleslgStudy

computer science

Binary heap

Binary heap is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Binary heap rather than just read about it. In short: A binary heap is a heap data structure that takes the form of a binary tree. Binary heaps are a common way of implementing priority queues.

Binary heap — main illustration
Binary heap — illustration

Key takeaways

  • Binary heap belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Binary heap to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Binary heap from memory before moving on to harder problems.

Reference excerpt

A binary heap is a heap data structure that takes the form of a binary tree. Binary heaps are a common way of implementing priority queues. The binary heap was introduced by J. W. J. Williams in 1964 as a data structure for implementing heapsort. 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:

Add the element to the bottom level of the heap at the leftmost open space. Compare the added element with its parent; if they are in the correct order, stop. 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:

Replace the root of the heap with the last element on the last level. Compare the new root with its children; if they are in the correct order, stop. 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 // A: an array representing the heap, indexed starting at 1 // i: the index to start at when heapifying down Max-Heapify(A, i): left ← 2×i right ← 2×i + 1 largest ← i if left ≤ length(A) and A[left] > A[largest] then: largest ← left if right ≤ length(A) and A[right] > A[largest] then: largest ← right if largest ≠ i then: swap A[i] and A[largest] Max-Heapify(A, largest)

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:

… excerpt ends here. Continue reading the full article.

Illustrations

Binary heap: Example of a complete binary max-heap
Example of a complete binary max-heap
Binary heap: Example of a complete binary min heap
Example of a complete binary min heap
Binary heap: A short animation depicting adding a value to a binary max-heap.
A short animation depicting adding a value to a binary max-heap.
Binary heap: A short animation depicting extracting a value from a binary max-heap.
A short animation depicting extracting a value from a binary max-heap.
Binary heap: A small complete binary tree stored in an array
A small complete binary tree stored in an array

Worked examples

Example 1 — a first encounter with Binary heap

Start with the simplest possible case. Write down what Binary heap claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Binary heap before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Binary heap ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Binary heap

In research
Binary heap appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Binary heap in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Binary heap is common in secondary-school and first-year university syllabi. It links to neighbouring topics Binary trees, Heaps (data structures), so understanding it makes those chapters shorter.
In everyday life
Look for Binary heap outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Binary heap” →

How to study Binary heap in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Binary heap means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Binary heap out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Binary heap in simple terms?

A binary heap is a heap data structure that takes the form of a binary tree. Binary heaps are a common way of implementing priority queues.

Why does Binary heap matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Binary heap?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Binary heap.

Tags

  • Binary trees
  • Heaps (data structures)

Keep exploring