Suppose you have a pile of numbers and you keep asking the same question: what is the smallest one right now? New numbers arrive, the smallest gets taken away, and you ask again. Scan the whole pile every time and you pay for it. Keep the pile fully sorted and every insertion is expensive. There is a cheaper middle ground.
A binary heap is that middle ground. It is nothing more than an array that obeys one rule: every element is smaller than or equal to its two children, where the children of position i live at positions 2i+1 and 2i+2. That single rule — the heap property — means the smallest element is always sitting at the very front, at index 0. No search required.
The magic is that you can insert a new value or remove the smallest while keeping that promise, each in just steps. The binary heap was invented by J. W. J. Williams in 1964 as the engine for a sorting method called heapsort. It is one of the cleanest, most-solved ideas in computer science — and it hides inside a structure you already know.
Comments
Loading comments...