7 - Heaps
Published online by Cambridge University Press: 10 November 2016
Summary
Priority Queues
One of the first data structures we encountered in Chapter 2 was a queue. The idea of dealing with some records on a FIFO – first in, first out – basis seems to be a reasonable choice and enjoys widespread acceptance. Nonetheless, there are situations in which the order should be different. A case in point would be the emergency room of any hospital: there is a constant influx of new potential patients, all waiting to being taken care of. However, they will be treated by order of medical urgency (which some professional has to assess) rather than by arrival time. Similarly, we all have many items on our to-do lists, but some of these items may be given a higher priority than others.
Translating the problem into mathematical terms, we are looking for a data structure we shall call a priority queue, storing a collection of records, each of which has been assigned a value considered as its priority. We wish to be able to perform updates, as inserting new elements, deleting others, or changing the priority of some. In addition, there should be fast access to the element with highest priority.
A simple solution could be a list that has been sorted by nonincreasing priority. The element with highest priority would then be the first, but updates might require time for a list of n records. Another option would be to use a search tree, which takes time to be built, as we shall see in Chapter 10, but then updating and extracting the maximum element can be done in time O(log n).
This chapter presents a better alternative. It uses a special form of a binary tree, called a heap and achieves O(log n) time updates and access to the maximum element in O(1). The time to build a heap of n elements is only O(n).
The name comes possibly from the fact that beside the rules given in the definition, there is little order between the elements of a heap, which conveys the impression of a disordered pile or elements that have been thrown one on another. It might remind many card games, in which the players throw cards in turn onto some pile, and only the top card is considered as being accessible.
- Type
- Chapter
- Information
- Basic Concepts in Data Structures , pp. 101 - 113Publisher: Cambridge University PressPrint publication year: 2016