views:

596

answers:

5

Besides the obvious answer of a Priority Queue, when would a heap be useful in my programming adventures?

+7  A: 

Use it whenever you need quick access to the largest (or smallest) item, because that item will always be the first element in the array or at the root of the tree.

However, the remainder of the array is kept partially unsorted. Thus, instant access is only possible to the largest (smallest) item. Insertions are fast, so it's a good way to deal with incoming events or data and always have access to the earliest/biggest.

Useful for priority queues, schedulers (where the earliest item is desired), etc...

A heap is a tree where a parent node's value is larger than that of any of its descendant nodes.

If you think of a heap as a binary tree stored in linear order by depth, with the root node first (then the children of that node next, then the children of those nodes next); then the children of a node at N are at 2N and 2N+1. This property allows quick access-by-index. And since heaps are manipulated by swapping nodes, this allows for in-place sorting.

Joe Koberg
Note also it can be a convenient guaranteed NlogN sort that doesn't require additional array allocations
Overflown
+2  A: 

Also good for selection algorithms (finding the min or max)

Dan
+1  A: 

The characteristic of a heap is that it is a structure that maintains data semiordered; thus, it is a good tradeoff between the cost of maintaining a complete order ant the cost of seaching through random chaos. That characteristic is used on many algorithms, such as selection, ordering, or classification.

Another useful characteristic of a heap is that it can be created in-place from an array!

Alex Ati
A: 

anytime when you sort a temporary list, you should consider heaps.

Javier
A: 

There are plenty of good answers here, so I'll chime in with "when a pile just isn't big enough."

Don Werve