Skip to content

Heap Data Structure (Binary Heap): Min-Heap, Max-Heap, Big O

A tree of nine glass spheres on brass rods against teal: a small sphere glowing amber at the top, two below it, then four, and two large spheres at the bottom left – the spheres grow larger towards the bottom

A heap is a binary tree that always keeps its smallest element at the root – or, as a max-heap, its largest. Unlike other trees, it needs no node objects with references to their children. You put its elements into an array level by level, and an element’s position in the array tells you where its children are.

You read the smallest element in O(1); inserting and removing cost O(log n). And you build a heap from n elements in O(n) – faster than you could sort them.

That is exactly what a priority queue needs: it always hands out the smallest element and keeps taking in new ones. That is why Java’s PriorityQueue is built on a heap – and, through it, so is Dijkstra’s algorithm, which always processes the node with the smallest distance from the start next. Heapsort carries the heap in its name: it turns an array into a max-heap and repeatedly removes the largest element from it – in the same array, without additional memory.

In this article, you will find out

  • what makes a heap and how a min-heap differs from a max-heap,
  • how a heap is stored in an array and how you calculate the indices of an element’s children and its parent from the element’s index,
  • how insertion (sift up), removal (sift down), and building a heap from an array work,
  • what time complexity each operation has and why building a heap costs only O(n) – with measurements,
  • how Java’s PriorityQueue implements the heap and how you use it as a max-heap,
  • what heaps are used for and which variants exist.

The Examples in This Article

You can find the code in the GitHub repository binary-tree: the example programs in the package eu.happycoders.binarytree.heap.example, the counting and benchmark programs in the package eu.happycoders.binarytree.heap.benchmark. The classes run on Java 17 or later.

The diagrams and most examples work with the same nine numbers: 3, 4, 6, 7, 9, 12, 13, 15, and 17.

What Is a Heap?

A heap is a binary tree with two properties:

  1. It is complete: All levels are fully occupied; only the lowest level may be missing nodes on the right. Such a tree is called a complete binary tree.
  2. It satisfies the heap property: Every node is less than or equal to its children. Such a heap is called a min-heap. If, conversely, every node is greater than or equal to its children, it is called a max-heap.

The following diagram shows a min-heap of the nine example numbers on the left. In the middle is a complete binary tree that violates the heap property: the 6 is above the 4. On the right is a tree that satisfies the heap property but is not complete: the 17 and the 13 hang from the 9, while the 12 to its left has no children.

Three binary trees of the numbers 3, 4, 6, 7, 9, 12, 13, 15, and 17. On the left a min-heap with the 3 at the root. In the middle the same tree with the 4 and the 6 swapped – the 6 is above the 4, the heap property is violated. On the right the 17 and the 13 hang from the 9 instead of from the 12 – the lowest level is not filled from the left, the tree is not complete
A heap and two trees that are not heaps

From the heap property it follows that the smallest element is at the root. For all other elements, the only rule is that the values never increase on the way to the root.

Siblings are in no particular order, and a node further down can be smaller than one further up on another branch – in the min-heap on the left, for example, the 6 is one level below the 7. So a heap is not sorted.

Min-Heap vs. Max-Heap

Min-heap and max-heap differ only in the direction of the comparison. You can build both heaps from the same nine numbers. The following diagram shows the min-heap from the previous section on the left and a max-heap with the 17 at the root on the right:

On the left a min-heap of the nine example numbers with the 3 at the root, on the right a max-heap of the same numbers with the 17 at the root
Min-heap and max-heap from the same numbers

The following table compares the two forms:

Min-heapMax-heap
At the root …the smallest elementthe largest element
Heap propertyparent ≤ childrenparent ≥ children
Typical usepriority queue, Dijkstra’s algorithmHeapsort (ascending sort)

Every algorithm for one heap works for the other if you reverse the comparison. In Java, that means a different Comparator – the section Heaps in Java shows what that looks like. In the rest of the article, I use the min-heap.

Array Representation of a Heap

You transfer a heap into an array by reading it level by level from left to right: the root goes to index 0, its children to indices 1 and 2, their children to indices 3 to 6, and so on. Because the tree is complete, no gaps arise. This turns the example heap into the array [3, 7, 4, 12, 9, 6, 15, 17, 13].

The example heap as a tree with levels 0 to 3 and below it as an array with indices 0 to 8: 3, 7, 4, 12, 9, 6, 15, 17, 13. Brackets under the array group the elements of each level: level 0 at index 0, level 1 at indices 1 and 2, level 2 at indices 3 to 6, level 3 at indices 7 and 8
A heap in an array: level by level from left to right

The array needs no references to children or parents. An element’s position determines where its children and its parent are – for the element at index i:

  • the left child at index 2i + 1,
  • the right child at index 2i + 2,
  • the parent at index (i − 1) / 2, rounded down.

The following diagram shows the three formulas for the 7 at index 1: its children 12 and 9 are at indices 3 and 4, its parent, the 3, at index 0.

The example heap as a tree and below it as an array with indices 0 to 8: 3, 7, 4, 12, 9, 6, 15, 17, 13. From the 7 at index 1, arrows labeled 2i + 1 and 2i + 2 lead to the children 12 and 9 at indices 3 and 4, and one labeled (i − 1) / 2 to the parent 3 at index 0
A heap in an array: from the index to the children and the parent

The height of the tree – the number of edges from the root to the lowest level – also follows from n, the number of elements: it is log2 n, rounded down. Each time the number of elements doubles, one level is added: nine elements have three levels below the root, a million elements have 19.

The class HeapIndexExample implements the three formulas as methods. With parent(), its method isMinHeap() checks whether an array represents a min-heap: it compares every element except the root with its parent. That is enough, because it checks every edge of the tree exactly once.

static int leftChild(int i) {
  return 2 * i + 1;
}

static int rightChild(int i) {
  return 2 * i + 2;
}

static int parent(int i) {
  return (i - 1) / 2;
}

static boolean isMinHeap(int[] a) {
  for (int i = 1; i < a.length; i++) {
    if (a[i] < a[parent(i)]) {
      return false;
    }
  }
  return true;
}

The class’s main() method calculates the indices of the children and of the parent of the 7 at index 1 and then checks two arrays: the example heap and a copy with the 5 instead of the 13 at index 8:

public static void main(String[] args) {
  int[] heap = {3, 7, 4, 12, 9, 6, 15, 17, 13};
  System.out.println("leftChild(1)  = " + leftChild(1));
  System.out.println("rightChild(1) = " + rightChild(1));
  System.out.println("parent(1)     = " + parent(1));
  System.out.println("isMinHeap: " + isMinHeap(heap));

  int[] notAHeap = {3, 7, 4, 12, 9, 6, 15, 17, 5};
  System.out.println("isMinHeap: " + isMinHeap(notAHeap));
}
leftChild(1)  = 3
rightChild(1) = 4
parent(1)     = 0
isMinHeap: true
isMinHeap: false

The first three lines of the output give the indices from the diagram. In the second array, the 5 at index 8 is smaller than its parent, the 12 at index 3 – that is why isMinHeap() returns false there.

Binary trees that are not complete can also be stored in an array, then with placeholders for missing nodes. The section Array Representation of a Binary Tree shows how.

Heap Operations

All examples in this section start with the example heap [3, 7, 4, 12, 9, 6, 15, 17, 13].

Reading the Minimum (Peek)

The smallest element of a min-heap is at the root, so at index 0 in the array. Reading it costs O(1), regardless of how many elements the heap contains.

Inserting and Removing

Inserting and removing change the heap, and both work in two steps:

  1. Keep the tree complete: A new element goes to the end of the array, and when removing, the last element moves to the vacated root.
  2. Repair the heap property: It can now only be violated around this one element. The element moves up or down the tree until it is in the right place.

Inserting: Sift Up

You append a new element to the end of the array. In the tree, that is the first free position on the lowest level, so the tree stays complete. However, the heap property may be violated if the new element is smaller than its parent.

In that case, you swap the element with its parent and check again at the new position – until the parent is smaller or equal or the element is at the root. Because the element rises in the tree, the procedure is called sift up.

The following diagram shows how the 5 gets into the example heap, in three steps:

  1. The 5 goes to the end of the array, which makes it the left child of the 9.
  2. The 5 is smaller than the 9 – the two swap places.
  3. The 5 is smaller than the 7 – the two swap again. The 3 at the root is smaller than the 5, so the insertion is complete.
Inserting the 5 into the example heap in three steps: the 5 is appended as the left child of the 9, swaps with the 9 and then with the 7, and stops below the 3. Afterwards, the array is 3, 5, 4, 12, 7, 6, 15, 17, 13, 9
Inserting with sift up

Each level costs at most one comparison and one swap. The path from the new leaf to the root is at most as long as the tree is high – so inserting costs O(log n).

Removing the Minimum: Sift Down

When you remove the root, a hole appears at the top of the tree. To keep the tree complete, the last element of the array moves to the root. There it usually violates the heap property, since it comes from the lowest level.

So you let it sink: you compare it with the smaller of its two children and swap the two if the child is smaller. You repeat this until no child is smaller or the element is a leaf. This procedure is called sift down.

The swap is always with the smaller child, because after the swap it is the parent of the other child. Swapped with the larger child, a larger parent would stand above the smaller child – the heap property would be violated elsewhere.

The following diagram removes the 3 from the example heap:

  1. The 13, the last element, moves to the root.
  2. The children of the root are the 7 and the 4. The 4 is the smaller child and smaller than the 13 – the two swap places. Had the 13 swapped with the 7, the 7 would now be above the 4.
  3. The children of the 13 are now the 6 and the 15. The 6 is smaller than the 13 – the two swap. The 13 is now a leaf, so the removal is complete.
Removing the 3 from the example heap in three steps: the 13 moves from the last position to the root, swaps with the smaller child 4 and then with the smaller child 6, and is then a leaf. Afterwards, the array is 4, 7, 6, 12, 9, 13, 15, 17
Removing the minimum with sift down

Each level costs two comparisons – one between the two children, one between the smaller child and the sinking element – and at most one swap. So removing also costs O(log n).

Building a Heap From an Array

If all elements are already there, there are two ways to a heap.

The obvious way: you insert the elements one after the other with sift up. In the worst case, every element rises to the root, and that costs O(n log n).

The faster way comes from Robert W. Floyd, who published it in 1964 under the title “Algorithm 245: Treesort 3”. You take the array as it stands, view it as a complete binary tree, and repair the heap property from the bottom up.

Every leaf is already a heap on its own. So you start with the last parent and let it sink with sift down, then the parent before it, and so on up to the root. When you let a node sink, the two subtrees below it are already heaps – after the sift down, the whole subtree from this node on is a heap, too.

The following diagram shows Floyd’s method on the array [6, 17, 15, 12, 9, 4, 3, 7, 13]. The last parent is the parent of the last element and is at index n / 2 − 1 (with n / 2 rounded down), so at index 3 for nine elements:

  1. Index 3: The 12 sinks below its smaller child, the 7.
  2. Index 2: The 15 sinks below the 3.
  3. Index 1: The 17 sinks two levels – first below the 7, then below the 12.
  4. Index 0: The 6 sinks below the 3, then below the 4.
Floyd’s method on the array 6, 17, 15, 12, 9, 4, 3, 7, 13 in four steps, from index 3 backwards to the root: the 12 swaps with the 7, the 15 with the 3, the 17 first with the 7 and then with the 12, the 6 first with the 3 and then with the 4. The result is the example heap 3, 7, 4, 12, 9, 6, 15, 17, 13
Building a heap from the bottom up (Floyd)

The result is the example heap [3, 7, 4, 12, 9, 6, 15, 17, 13], after six swaps. Floyd’s method costs only O(n). The section Time Complexity of Heapify: Why Building a Heap Costs Only O(n) shows why.

By the way, in Python’s heapq module and in Java’s PriorityQueue, heapify() is the name of the whole construction according to Floyd. Some textbooks, however, already use that name for letting a single node sink – in this article, that is sift down.

Searching

To find out whether a heap contains a particular element, you can search through the tree and skip entire subtrees: if a node in a min-heap is larger than the element you are looking for, so are all nodes below it. If you search for the 9 in the example heap, you visit the 3, the 7, the 12, and the 9 – you skip the 17 and the 13 below the 12.

In the worst case, that does not help. If you search for an element that is larger than all elements in the heap, no node is larger than the one you are looking for, and you visit all of them – O(n). Java’s PriorityQueue does not even try: its contains() method runs through the array from front to back and compares each element using equals().

If you need fast search, the heap is the wrong data structure; the section Heap vs. Other Data Structures shows which one fits better.

Changing or Removing an Arbitrary Element

You first have to find an element in the middle of the heap – as described in the previous section, that costs O(n) in the worst case.

Once you know the element’s position, the rest costs only O(log n):

  • Removing: The last element moves to the vacated position. It may be too large or too small there, so you first try sift down and, if it has not moved, sift up. That is exactly what the removeAt() method of Java’s PriorityQueue does.
  • Decreasing the value: A smaller value can only violate the heap property with respect to the parent, so you let the element rise with sift up. This operation is called decrease key.
  • Increasing the value: A larger value can only violate the heap property with respect to the children, so you let the element sink with sift down.

The search is no longer needed if the heap remembers the position of each element, for example in a HashMap from element to index. This variant is called an indexed heap; sift up and sift down then also have to update the map with every swap. Decrease key then costs O(log n) instead of O(n) – and Dijkstra’s algorithm needs exactly this operation every time it finds a shorter path to a node.

Java’s PriorityQueue has no such index. Dijkstra’s algorithm still works efficiently with it: instead of changing a node’s entry, it inserts a second entry with the shorter distance and skips the outdated one when poll() returns it later. This technique is called lazy deletion; the article on Dijkstra’s algorithm shows it in the section PriorityQueue Without remove(): Lazy Deletion.

Time Complexity of Heap Operations

The following table summarizes the time complexity of the operations of a binary heap with n elements, with the reason in a few words:

OperationTime complexityReason
Read the minimumO(1)it is at index 0
InsertO(log n)sift up, at most one swap per level
Remove the minimumO(log n)sift down, at most one swap per level
Build from n elements (Floyd)O(n)most nodes hardly sink – see below
Build by inserting n timesO(n log n)in the worst case; O(n) on average
SearchO(n)the heap is not sorted
Remove an arbitrary elementO(n)search in O(n), then O(log n)
Decrease key with indexO(log n)position from the map, then sift up
Merge two heapsO(n + m)append both arrays, then Floyd

In the last row, the second heap has m elements. The operations need no additional memory, because they work in the array itself – the space required beyond the elements is O(1). Only the indexed heap needs an additional O(n) for its map.

Time Complexity of Heapify: Why Building a Heap Costs Only O(n)

At first glance, Floyd’s method costs O(n log n): it lets n / 2 parents sink, and each sift down can cost up to log2 n swaps. This calculation overlooks that most nodes are far down – and a node can sink at most as many levels as there are below it.

The following diagram shows this for a perfect binary tree with 15 nodes. Next to each level is how many nodes it has and how many levels each of them sinks at most:

  • the eight leaves, about n / 2, do not sink at all,
  • the four nodes above them, about n / 4, at most one level,
  • the two nodes above those, about n / 8, at most two levels,
  • the root at most three levels.
A perfect binary tree with 15 nodes on four levels. Next to the levels, from bottom to top: 8 nodes, sink 0 levels; 4 nodes, at most 1 level; 2 nodes, at most 2 levels; 1 node, at most 3 levels
The lower a node, the less it can sink

So the maximum number of swaps S for a heap with n elements is:

S = 1 · n/4 + 2 · n/8 + 3 · n/16 + 4 · n/32 + ...

You can simplify this sum by subtracting it from its double. The double is:

2S = 1 · n/2 + 2 · n/4 + 3 · n/8 + 4 · n/16 + ...

Doubling halves every denominator, and the factor in front of it stays: 1 · n/4 becomes 1 · n/2, 2 · n/8 becomes 2 · n/4. Every term thus moves one place forward. The same fraction is therefore one place further back in S than in 2S and has a factor that is smaller by 1 there: n/4 is the second term in 2S with the factor 2, the first in S with the factor 1.

So when you subtract S, you subtract each term from the term in 2S with the same fraction – not from the one in the same place. The following diagram therefore writes S under 2S, shifted by one place. For each fraction, the factor 1 remains, and the first term of 2S, 1 · n/2, has no partner and stays as it is:

Three rows, one below the other, aligned in columns by fraction. At the top 2S: 1 · n/2, 2 · n/4, 3 · n/8, 4 · n/16. Below it − S, shifted one column to the right: an empty cell under n/2, then 1 · n/4, 2 · n/8, 3 · n/16. Below a line 2S − S: 1 · n/2, 1 · n/4, 1 · n/8, 1 · n/16
Subtracting S from 2S, shifted by one place

What remains is:

2S − S = n/2 + n/4 + n/8 + n/16 + ...

The left side is nothing but S, the right side n times the sum 1/2 + 1/4 + 1/8 + ... This sum approaches 1 without reaching it. So S < n: Floyd’s method swaps fewer than n times. Each sift down makes at most two comparisons per level, so the number of comparisons is linear, too. Building a heap costs O(n).

Measured: Floyd’s Method vs. Inserting One by One

I counted how big the difference in comparisons is. The program HeapConstructionCount builds a min-heap from 1,000 to one million distinct numbers – once with Floyd’s method, once by inserting one by one – and counts the comparisons. The numbers come shuffled, in ascending order, or in descending order. For a min-heap, ascending input is the best case for inserting one by one (no element rises), descending input the worst case (every element rises to the root).

The following chart shows the comparisons per element over the number of elements:

Line chart: comparisons per element for 1,000, 10,000, 100,000, and 1,000,000 elements. Floyd’s method stays flat at 1.9 (random input) and 2.0 (descending input). Inserting one by one stays flat at 2.3 on random input and rises on descending input from 8.0 through 11.4 and 14.7 to 18.0. On ascending input, both methods share one line at 1.0
Comparisons per element when building a min-heap

The three lines around 2.0 comparisons almost overlap in the chart. Their values and the course of the other lines:

  • Floyd’s method stays flat on every input: 1.9 comparisons per element on random input, 2.0 on descending input.
  • Inserting one by one also stays flat on random input, at 2.3 comparisons per element.
  • On ascending input, both methods are on the gray line at the bottom: numbers sorted in ascending order already form a min-heap, no element moves, and both methods need exactly n − 1 comparisons – 1.0 per element.
  • Inserting one by one on descending input grows with log n: from 8.0 comparisons per element at 1,000 elements to 18.0 at one million. That is 17,951,445 comparisons versus 1,999,974 with Floyd’s method – nine times as many.

So the advantage of Floyd’s method lies in the worst case (descending input): it guarantees O(n). Inserting one by one achieves O(n) only on average.

Measured on the PriorityQueue: Constructor vs. addAll()

I measured the difference in milliseconds on Java’s PriorityQueue. Its constructor builds the heap from a collection with Floyd’s method; its addAll() method inserts the elements one by one. The table shows how long each takes for one million elements:

Input (1 million elements)ConstructoraddAll()
random7.7 ms13.0 ms
ascending0.8 ms2.9 ms
descending2.1 ms19.4 ms

The constructor is 1.7 times as fast as addAll() on random input and nine times as fast on descending input.

On random input, however, the constructor takes 3.6 times as long as on descending input (7.7 vs. 2.1 ms), even though it makes fewer comparisons (1.88 vs. 2.00 per element). The reason is the processor’s branch prediction: at every branch, it predicts which path will be executed, and on a wrong prediction it has to discard the instructions it has already started.

On descending input, the right child is the smaller one at every sift down, and every element sinks all the way down. The processor predicts every branch correctly. On random input, every decision about which child is smaller is a coin toss.

Heaps in Java

The JDK has no Heap class. Its role is taken by the class java.util.PriorityQueue: it stores its elements as a binary min-heap in an Object[], and its internal methods are named like the operations in this article – siftUp(), siftDown(), and heapify().

If you pass a collection to the constructor, the PriorityQueue builds a heap from it with Floyd’s method in O(n). If the collection is a SortedSet or another PriorityQueue, it adopts their order directly, because that order already satisfies the heap property. addAll(), in contrast, inserts each element individually with sift up.

You get a max-heap by passing the comparator Comparator.reverseOrder() to the PriorityQueue constructor. The following program builds, from the nine example numbers [6, 17, 15, 12, 9, 4, 3, 7, 13] (in the same order the section Building a Heap From an Array used to show Floyd’s method), first a min-heap via the constructor and then a max-heap via addAll(). It then removes all elements of the max-heap with poll() (class PriorityQueueHeapExample):

public static void main(String[] args) {
  List<Integer> numbers = List.of(6, 17, 15, 12, 9, 4, 3, 7, 13);

  PriorityQueue<Integer> minHeap = new PriorityQueue<>(numbers);
  System.out.println("min-heap: " + minHeap);

  PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
  maxHeap.addAll(numbers);
  System.out.println("max-heap: " + maxHeap);

  List<Integer> polled = new ArrayList<>();
  while (!maxHeap.isEmpty()) {
    polled.add(maxHeap.poll());
  }
  System.out.println("poll():   " + polled);
}
min-heap: [3, 7, 4, 12, 9, 6, 15, 17, 13]
max-heap: [17, 13, 15, 12, 9, 4, 3, 6, 7]
poll():   [17, 15, 13, 12, 9, 7, 6, 4, 3]

The first line of the output shows that the constructor built exactly the example heap from the diagram of Floyd’s method – toString() prints the internal array in its order. In the second line, the 17 is at the root of the max-heap; the other elements are only as ordered as the heap property requires. Only removing them with poll() returns the elements in order of size, as the third line shows.

The program fills the max-heap with addAll() because up to Java 27 there is no constructor that takes a collection and a comparator. As of Java 28, new PriorityQueue<>(numbers, Comparator.reverseOrder()) also builds a max-heap with Floyd’s method.

What else the PriorityQueue can do – comparator, iterator, the time complexity of its methods – is covered in the article Java PriorityQueue. The thread-safe PriorityBlockingQueue also stores its elements in a binary heap. How to implement a min-heap yourself, with sift up and sift down in code, is shown in the article Priority Queue Implementation in Java Using a Min-Heap.

Heap vs. Other Data Structures

The heap is not the only data structure that quickly returns a minimum. The following table compares it with a balanced binary search tree and an array sorted in descending order, whose minimum is at the end:

OperationHeapBalanced binary search treeSorted array
Read the minimumO(1)O(log n)O(1)
InsertO(log n)O(log n)O(n)
Remove the minimumO(log n)O(log n)O(1)
SearchO(n)O(log n)O(log n)
Iterate in sorted orderO(n log n) (remove all)O(n)O(n)
Build from n elementsO(n)O(n log n)O(n log n)

I recommend the heap when you repeatedly need the smallest (or largest) element and insert elements in between. If, on the other hand, you need search or sorted iteration, use a balanced binary search tree – in Java, a TreeSet or a TreeMap. The sorted array only pays off if you rarely insert. You can find the detailed comparison of heap and search tree in the section Binary Search Tree vs. Heap.

By the way, heap and priority queue are not the same thing: the priority queue is an abstract data type – it only defines the operations – and the heap is the usual data structure used to implement it. More on this in the article Priority Queue Implementation in Java Using a Min-Heap.

Applications of Heaps

A heap pays off wherever a program repeatedly needs the smallest or largest element of a set that changes in between:

  • Priority queues: Java’s PriorityQueue is a min-heap, and so is the PriorityBlockingQueue. Both use poll() to remove the smallest element at the root.
  • Heapsort: Heapsort builds a max-heap from the array and then keeps swapping the root to the end of the still unsorted part until the array is sorted – in O(n log n) and without additional memory.
  • Shortest paths: Dijkstra’s algorithm and the A* search algorithm take the node with the smallest (for A*: estimated) total distance in each step – often from a min-heap such as the PriorityQueue.
  • Merging sorted lists: A min-heap holds the first not-yet-merged element of each list – k elements for k lists. For each element, the heap remembers which list it comes from. You remove the smallest element and add the next element from the same list – O(n log k) in total for n elements.

I will show two applications in more detail.

Finding the k Largest Elements

If you only need the k largest of a very large number of elements, you do not have to sort everything. A min-heap with at most k elements is enough: its root is the smallest of the k largest elements you have seen so far. If a new element is larger than the root, it replaces it and the next smallest element moves into the root’s place; otherwise, it is dropped. Each step costs O(log k), all n steps together O(n log k) – sorting all n elements, on the other hand, would cost O(n log n).

The method largest() implements this with a PriorityQueue and returns the k largest elements sorted in descending order (class TopKExample):

static List<Integer> largest(int[] numbers, int k) {
  PriorityQueue<Integer> heap = new PriorityQueue<>();
  for (int number : numbers) {
    if (heap.size() < k) {
      heap.offer(number);
    } else if (number > heap.peek()) {
      heap.poll();
      heap.offer(number);
    }
  }
  List<Integer> result = new ArrayList<>(heap);
  result.sort(Comparator.reverseOrder());
  return result;
}

The class’s main() method finds the five largest of one million random numbers between 0 and one billion:

public static void main(String[] args) {
  int[] numbers = new Random(42).ints(1_000_000, 0, 1_000_000_000).toArray();
  System.out.println(largest(numbers, 5));
}
[999998715, 999997530, 999995008, 999995002, 999993916]

The heap never contains more than five elements, no matter how many numbers pass through. That is why the method also works for a data stream that does not fit into memory.

By the way, poll() followed by offer() is double work: a heap of your own could replace the root in a single step by writing the new element to the root and letting it sink with sift down. The PriorityQueue offers no method for this. It does not matter here – with one million random numbers, the program replaces an element only 51 times; all other numbers already fail the comparison with peek().

Calculating the Median Continuously

You keep the median of a growing sequence of numbers up to date with two heaps: a max-heap holds the smaller half of the numbers, a min-heap the larger half. If a new number is smaller than the root of the max-heap – the largest element of the smaller half – it goes into the max-heap, otherwise into the min-heap. If one of the two is then larger than the other by more than one element, its root moves to the other heap.

The median is then the root of the larger heap or, if both are the same size, the mean of both roots. A new number thus costs O(log n), reading the median O(1).

Other Types of Heaps

Besides the binary heap, there are heap variants that make individual operations faster.

d-ary Heap

In a d-ary heap, introduced by Donald B. Johnson in 1975, each node has up to d children instead of two. In the array, the children of the element at index i are at indices d · i + 1 to d · i + d, its parent at index (i − 1) / d, rounded down. This makes the tree flatter: its height is logd n instead of log2 n.

Insertion benefits from this, because sift up compares with only one parent per level. Sift down, on the other hand, has to compare all d children per level and becomes more expensive. Counted for one million shuffled numbers that are first inserted and then removed again:

dHeightComparisons per element:
insert
Comparisons per element:
remove
Elements moved
per removal
Time for everything
2192.2834.9117.3168.6 ms
4101.5536.238.9741.5 ms
871.3049.776.1739.8 ms

The 4-ary heap makes almost as many comparisons in total as the binary heap (37.8 vs. 37.2 per element), but moves only half as many elements when removing and is 1.65 times as fast (41.5 vs. 68.6 ms). The 8-ary heap needs 35% more comparisons than the 4-ary heap and is only 4% faster than it at one million elements – and even slower at 1,000 and 100,000 elements.

Binomial Heap, Fibonacci Heap, and Pairing Heap

Three other heaps do not store their elements in an array. The binomial heap, the Fibonacci heap, and the pairing heap consist of trees whose nodes have any number of children and are connected by references. This lets them merge two heaps faster than the binary heap, and the Fibonacci and pairing heaps lower the cost of the decrease-key operation.

The following table compares the time complexities of the binary heap and its four variants, based on the overview in the Wikipedia article “Heap (data structure)”. The values for decrease key in the binary and the d-ary heap apply to an indexed heap that knows the position of each element; without an index, the search adds O(n) (see Changing or Removing an Arbitrary Element):

HeapRead minimumInsertRemove minimumDecrease keyMerge
Binary heapO(1)O(log n)O(log n)O(log n)O(n)
d-ary heapO(1)O(logd n)O(d logd n)O(logd n)O(n)
Binomial heapO(1)O(1) amortizedO(log n)O(log n)O(log n)
Fibonacci heapO(1)O(1)O(log n) amortizedO(1) amortizedO(1)
Pairing heapO(1)O(1)O(log n) amortizedo(log n) amortizedO(1)

“Amortized” means that a single operation can be more expensive, but averaged over any sequence of operations, the stated time complexity holds. For decrease key in the pairing heap, no fixed complexity class has been proven. All that has been proven is that the cost grows more slowly than log n (Seth Pettie, “Towards a Final Analysis of Pairing Heaps”, 2005) – hence the small o.

With the Fibonacci heap, Dijkstra’s algorithm achieves a time complexity of O(n log n + m) for n nodes and m edges. In my measurement in the article on Dijkstra’s algorithm, it was nevertheless slower than the PriorityQueue with lazy deletion: 368 ms vs. 266 ms at 300,625 nodes.

Min-Max Heap

The min-max heap is a complete binary tree in an array like the binary heap. Every node on a level at an even distance from the root is less than or equal to all nodes below it, and every node on the other levels is greater than or equal to all nodes below it. This puts the minimum at the root and the maximum at one of its two children – the min-max heap returns both in O(1).

Summary

A heap is a complete binary tree in which every node is less than or equal to its children (min-heap) or greater than or equal to them (max-heap). It is stored without gaps in an array; the children of the element at index i are at 2i + 1 and 2i + 2, its parent at (i − 1) / 2.

You read the minimum in O(1); inserting (sift up) and removing (sift down) cost O(log n), searching O(n). Floyd’s method builds a heap from n elements in O(n) – for one million numbers in descending order, with one ninth of the comparisons that inserting one by one needs. In Java, the PriorityQueue is this heap; its constructor uses Floyd’s method, addAll() does not.

Where to go from here depends on your task:

Did this article answer your questions? Then I’d be happy about a review on my ProvenExpert profile – it helps other developers find this content.

👉 Leave a review

Want Even More Knowledge?

My blog features many articles on Java, software architecture, and performance — from foundational concepts to advanced patterns.

If you want to go deeper, check out my trainings: hands-on, easy to understand, and directly applicable to your day-to-day project work. Instead of theory, I teach principles that help you write code that is better, more maintainable, and more performant in the long run.

Explore the Java Trainings

Become a Better Java Developer

My free newsletter keeps you ahead. Modern Java: new versions & features, performance, and JVM insights – once a month.

Search