Heaps vs. Ordered Arrays
Now that you know the efficiency of heaps, let’s see why it’s a great choice for implementing priority queues.
Here’s a side-by-side comparison of ordered arrays versus heaps:
Ordered Array | Heap | |
|---|---|---|
Insertion | O(N) | O(log N) |
Deletion | O(1) | O(log N) |
At first glance, it seems that it’s a wash. Ordered arrays are slower than heaps when it comes to insertion but faster than heaps for deletion.
However, heaps are considered to be the better choice, and here’s why.
While O(1) is extremely fast, O(log N) is still very fast. And O(N), by comparison, is slow. With this in mind, we can rewrite the earlier table this way:
Ordered Array | Heap | |
|---|---|---|
Insertion | Slow | Very fast |
Deletion | Extremely fast | Very fast |
In this light, it becomes clearer as to why the heap ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access