








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









In this chapter we examine yet another variation on the simple Bag data structure. A priority queue maintains values in order of importance. A metaphor for a priority queue is a to-do list of tasks waiting to be performed, or a list of patients waiting for an operating room in a hospital. The key feature is that you want to be able to quickly find the most important item, the value with highest priority. Like a bag, you can add new elements into the priority queue. However, the only element that can be accessed or removed is the one value with highest priority. In this sense the container is like the stack or queue, where it was only the element at the top or the front of the collection that could be removed.
The traditional definition of the Priority Queue abstraction includes the following operations: add (newelement) Add a new value to queue first () Return first element in queue removeFirst () Remove first element in queue isEmpty() Return true if collection is empty Normally priority is defined by the user, who provides a comparison function that can be applied to any two elements. The element with the largest (or sometimes, the smallest) value will the deemed the element with highest priority. A priority queue is not, in the technical sense, a true queue as described in Chapter 7. To be a queue, elements would need to satisfy the FIFO property. This is clearly not the case for the priority queue. However, the name is now firmly attached to this abstraction, so it is unlikely to change. The following table shows priority queue operation names in the C++ STL and in the Java class PriorityQueue. Operation C++ STL class priorityQueue
In C++ it is the element with the largest value, as defined by the user provided comparison function, that is deemed to be the first value. In the Java library, on the other hand, it is the element with the smallest value. However, since the user provides the comparison function, it is easy to invert the sense of any test. We will use the smallest value as our first element.
The most common use of priority queues is in simulation. A simulation of a hospital waiting room, for example, might prioritize patients waiting based on the severity of their need. A common form of simulation is termed a “discrete, event-driven simulation”. In this application the simulation proceeds by a series of “events”. An event is simply a representation of an action that occurs at a given time. The priority queue maintains a collection of events, and the event with highest priority will be the event with lowest time; that is, the event that will occur next. For example, suppose that you are simulating patrons arriving at a small resturant. There are three main types of event of interest to the simulation, namely patrons arriving (the arrival event), patrons ordering (the order event) and patrons leaving (the leave event). An event might be represented by a structure, such as the following: struct eventStruct { int time; int groupsize; enum {arrival, order, leave} eventType; }; To initialize the simulation you randomly generate a number of arrival events, for groups of various sizes, and place them into the queue. The execution of the simulation is then described by the following loop: while the event queue is not empty select and remove the next event do the event, which may generate new events To “do” the event means to act as if the event has occurred. For example, to “do” an arrival event the patrons walk into the resturant. If there is a free table, they are seated and an subsequent “order” event is added to the queue. Otherwise, if there is not a free table, the patrons either leave, or remain in a queue of waiting patrons. An “order” event produces a subsequent “leave” event. When a “leave” event occurs, the newly emptied table is then occupied by any patrons waiting for a table, otherwise it remains empty until the next arrival event. Many other types of simulations can be described in a similar fashion.
removeFirst()
In a worksheet you will explore two alternative implementation techniques for priority queues that are based around the idea of storing values in a type of representation termed a heap. A heap is a binary tree that also maintains the property that the value stored at every node is less than or equal to the values stored at either of its child nodes. This is termed the heap order property. The classic heap structure (known just as the heap) adds the additional requirement that the binary tree is complete. That is, the tree if full except for the bottom row, which is filled from left to right. The following is an example of such a heap: A note on Encapsulation There are two choices in developing a new container such as the one described above. One choice is to simply add new functions, or extend the interface, for an existing data structure. Sometimes these can make use of functionality already needed for another purpose. The balanced binary tree, for example, already needed the ability to find the leftmost child in a tree, in order to implement the remove operation. It is easy to use this function to return the first element in the three. However, this opens the possibility that the container could be used with operations that are not part of the priority queue interface. An alternative would have been to create a new data structure, and encapsulate the underlying container behind a structure barrier, using something like the following: struct SortedHeap { struct AVLtree data; }; We would then need to write routines to initialize this new structure, rather than relying on the existing routines to initialize an AVL tree. At the cost of an additional layer of indirection we can then more easily guarantee that the only operations performed will be those defined by the interface. There are advantages and disadvantages to both. The bottom line is that you, as a programmer, should be aware of both approaches to a problem, and more importantly be aware of the implications of whatever design choice you make.
Notice that a heap is partially ordered, but not completely. In particular, the smallest element is always at the root. Although we will continue to think of the heap as a tree, we will make use of the fact that a complete binary tree can be very efficiently represented as an array. To root of the tree will be stored as the first element in the array. The children of node i are found at positions 2i+1 and 2i+2, the parent at (i-1)/2. You should examine the tree above, and verify that the transformation given will always lead you to the children of any node. To reverse the process, to move from a node back to the parent, simply subtract 1 and divide by 2. You should also verify that this process works as you would expect. We will construct our heap by defining functions that will use an underlying dynamic array as the data container. This means that users will first need to create a new dynamic array before they can use our heap functions: struct dyArray heap; /* create a new dynamic array / dyArrayInit (&heap, 10); / initialize the array to 10 elements */ … To insert a new value into a heap the value is first added to the end. (This operation has actually already been written in the function dyArrayAdd). Adding an element to the end preserves the complete binary tree property, but not the heap ordering. To fix the ordering, the new value is percolated up into position. It is compared to its parent node. If smaller, the node and the parent are exchanged. This continues until the root is reached, or the new value finds its correct position. Because this process follows a path in a complete binary tree, it is O(log n). The following illustrates adding the value 4 into a heap, then percolating it up until it reaches its final position. When the value 4 is compared to the 2, the parent node containing the 2 is smaller, and the percolation process halts.
When a value is removed from a heap the size of the heap is reduced. If the heap is being represented in an array, this means that the bottom-most element of the array is no longer being used. (Using the terminology of the dynamic array we examined earlier, the size of the collection is smaller, but the capacity remains unchanged). original heap remove front move last reheap What if we were to store the removed values in the now unused section of the array? In fact, since the last element in the array is always moved into the hole made by the removal of the root, it is a trivial matter to simply swap this value with the root. Suppose we repeat this process, always swapping the root with the currently last element, then reheaping by percolating the new root down into position. The result would be a sorting algorithm, termed heap sort. The following is a snapshot illustrating heap sort in the middle of execution. Notice that the smallest elements have been moved to the right. The current size of the dynamic array is indicated by the sharp drop in values. The
elements to the left of this point are organized in a heap. Notice that the heap is not completely ordered, but has a tendency towards being ordered. To determine the algorithmic execution time for this algorithm, recall that adjustHeap requires O(log n) steps. There are n executions of adjustHeap to produce the initial heap. Afterwards, there are n further executions to reheap values during the process of sorting. Altogether the running time is O(n log n). This matches that of merge sort, quick sort, and tree sort. Better yet, heap sort requires no additional storage. Question : Simulate execution of the Heap sort algorithm on the following values: 9 3 2 4 5 7 8 6 1 0 First make the values into a heap (the graphical representation is probably easier to work with than the vector form). Then repeatedly remove the smallest value, and rebuild the heap.
In a heap the relative order of the left and right children is unimportant. The only property that must be preserved is that each node is smaller than either of its children. However, the heap order property does not insist that, for example, a left child is smaller than a right child. The skew heap builds on this flexibility, and results in a very different organization from the traditional heap. The skew heap makes two observations. First, left and right children can always be exchanged with each other, since their order is unimportant. Second, both insertions and removals from a heap can be implemented as special cases of a more general task, which is to merge two heaps into one.
} else { Node temp = right.right right.right = merge(right.left, left) right.left = temp return right } In worksheet 35 you will complete the implementation of the SkewHeap based on these ideas. Like the self organizing list described in Chapter 8, a skew heap is an example of a data structure that tries to optimize future performance based on past operations. It makes no guaranteed that poorly balanced trees cannot arise, but if they do they are quickly taken apart so that they cannot have a lasting impact on execution time. To measure the relative performance of the Heap and SkewHeap abstractions, an experiment was conducted in which n random integers between 0 and 100 were inserted into a heap and then removed. A plot of the execution times for various values of n was obtained as follows. The result indicates that even through the SkewHeap is performing many more memory allocations than the Heap, the overall execution time is still faster. Short Exercises
Self Study Questions 1. What are the abstract operations that characterize a priority queue? 2. Give an example of a priority queue that occurs in a non-computer science situation. 3. Describe how a priority queue is similar to a bag, and how it is different. Describe how a priority queue is similar to a queue, and how it is different. 4. Why is a priority queue not a true queue in the sense described in Chapter 7?
operations of insertion or removal must be very rapid. Thus, when measured over several operations the performance of a skew heap is very impressive. Programming Exercises
b. The root of T1 is the root of the new heap. The right shild is recursively merged with T c. If the resulting height of the right child is larger than the left child, the two children are reversed d. The height of the result is set to one lrger than the height of the left child. Because the merge is always performed with a right child, which is always has a height smaller than the left child, the result is produced very quickly. Provide an implementation of a heap data structure based on this principle. On the Web The wikipedia contains articles explaining the priority queue abstraction, as well as the heap data structure, and the associated heap sort algorithm. The entry for heap contains links to several variations, including the skew heap, as well as others. Wikipedia also contains a good explanation of the concept of Discrete Event Simlation. The on-line Dictionary of Algorithms and Data Structures contains explanations of heap, the heapify algorithm, and other topics discussed in this chapter.