Heaps and Priority Queues

Priority Queues

A priority queue is a queue where removal depends not upon order of insertion but upon importance.

The key gives an element’s importance. Keys must have a comparison operation that is reflexive, antisymmetric, and transitive.

Such a queue is straightforwardly implemented using a list. There are two strategies: sorted and unsorted.

A priority queue gives a straightforward scheme for sorting: Insert all elements into the priority queue and simply read them back out.

The priority queue sorting scheme, implemented using sorted and unsorted lists, gives rise to the insertion-sort and selection-sort algorithms, respectively. Both are \(O(n^2)\).

If we can improve the performance of the priority queue, we can naturally improve the performance of sorting.

Heaps

A heap:

Applying the priority queue sorting scheme to a heap results in an \(O(n\log n)\) sort.

The array representation of the heap also gives rise to an extremely efficient in-place sorting algorithm.