Heap
A heap is a collection that always gives back the smallest element first (min heap), or the greatest one (max heap). You should use a heap whenever you repeatedly need the smallest or the greatest element of a collection that keeps changing.
A heap is the common way to implement a priority queue, so the two names are often used for the same thing.
Time complexity
| operation | time |
|---|---|
| read the smallest element | |
| add an element | |
| remove the smallest element |
Implementation
We build a min heap, where the smallest element is on top. A max heap is the same with every comparison reversed.
Array layout
A heap is a binary tree stored in an array. Index 0 is the root, and the children of index are at and . Every parent is less than or equal to its children, so the smallest element is at index 0.
Push the element
A new element goes to the end of the array. Then we move the element up, swapping it with its parent until the parent is smaller.
This takes at most.
Pop the element
We swap the root with the last element and remove it from the end. Then we move the new root down, swapping it with its smaller child until both children are greater.
This takes at most.
Build it
Implement push, pop and peek in the class below. The index helpers and the code that uses the heap are already written.