COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III
2 Topics Priority Queues Heaps Heap Sort
3 ADT Priority Queue Appropriate for data that don't need to be searched by search key Example: Emergency Room in a hospital Patients are treated in the order of their arrival Some priority would be assigned for some patients The next available doctor should treat the patient with the highest priority A priority value is added to the record representing the items and is assigned to indicate the task's priority for completion Larger priority values indicate highest priority
4 ADT Priority Queue
5 Possible Implementations Array-Based Items are maintained in ascending sorted order of priority value Item with highest priority value is at the end of the array pqDelete returns the item in Items [Size - 1] pqInsert uses binary search to find the correct position, then shift array elements to make room to the new item
6 ADT Priority Queue Possible Implementations Array-Based Items are maintained in ascending sorted order of priority value Item with highest priority value is at the end of the array pqDelete returns the item in Items [Size - 1] pqInsert uses binary search to find the correct position, then shift array elements to make room to the new item (O(?))
7 ADT Priority Queue Possible Implementations Reference-Based??
8 ADT Priority Queue Possible Implementations Reference-Based Items are maintained in descending order of priority values The highest priority value is at the beginning of the linked list pqDelete returns the item in PQ_Head, then changes PQ_Head to “point” to the next item (O(?)) pqInsert must traverse the list to find the correct position, then insert the element by “pointer” manipulation (O(?))
9 ADT Priority Queue Possible Implementations BST ???
10 ADT Priority Queue Possible Implementations BST pqInsert is the same as TableInsert (O(?)) pqDelete is easier because the highest priority value is always in the rightmost node of the tree (O(?))
11 ADT Priority Queue Conclusion A BST is good for both tables & priority queues If the table application primarily involves retrievals & traversals, the balance of the tree isn't affected Because priority queues involve mostly insertions & deletions, which can affect the shape of the tree, a balanced variation of the tree will be needed If you know the maximum size of the priority queue, an array-based implementation is better
12 Review A priority queue orders its items by their ______. position value priority value size
13 Review The first item to be removed from a priority queue is the item ______. in the front of the priority queue in the end the priority queue with the highest value with the highest priority value
14 Review In an array-based implementation of the priority queue, the pqDelete operation returns the item in ______. items[size] items[0] items[size-1] items[size+1]
15 Review In a linear implementation of the priority queue based on a linked list, the item with the highest priority value is located ______. at the beginning of the linked list at the end of the linked list in the middle of the linked list at a random location in the linked list
16 Review In a binary search tree implementation of the ADT table, the item with the highest priority value is always in the ______. root of the tree leftmost node of the tree rightmost node of the tree leftmost node at level 1 of the tree
17 Heaps Heap: A complete binary tree with the following characteristics: The tree is Empty binary tree, or Its Root contains a search key >= (for a Maxheap) or <= (for Minheap) Search key of its children, and The subtrees are also Heaps The search keys of the children have no relationship; you don't know which child has the larger (smaller) search key The heap is always complete and balanced
18 Heaps Special Heaps: Max-Heap: The heap with the largest item's search key in its root Min-Heap: The heap with the smallest item's search key in its root Semi-Heap: When the root isn't the largest, but both subtrees are heaps
19 Heaps max heap min heap min heap
20 ADT Heap Operations
21 ADT Heap's Array-Based Implementation An array and an integer counter are needed Array of heap items Size: number of items in the heap If the root is deleted, a semi-heap might result. In such case the heap has to be rebuilt to preserve the heap property
22 ADT Heap's Array-Based Implementation Example: Deletion Delete 10 IndexContents
23 ADT Heap's Array-Based Implementation Example: Deletion Delete 10 we get 2 disjoint heaps IndexContents st Heap2 nd Heap
24 ADT Heap's Array-Based Implementation Example : Deletion Put 5 instead of 10 We get a semi-heap IndexContents
25 ADT Heap's Array-Based Implementation Example: Deletion Trickle down We get a heap back IndexContents
26 ADT Heap's Array-Based Implementation Example: Deletion heapRebuild (items, root, size) //convert a semiheap into a heap
27 ADT Heap's Array-Based Implementation Example: Insertion Insert
28 ADT Heap's Array-Based Implementation Example: Insertion Tickle-up
29 ADT Heap's Array-Based Implementation Example: Insertion Tickle-up
30 ADT Heap's Array-Based Implementation public class Heap { private int MAX_HEAP =100; private KeyedItem [] items; // array of heap items private int size; // number of heap items public Heap () { items = new KeyedItem [MAX_HEAP]; size =0; } public bool heapIsEmpty() { return size == 0; } // end heapIsEmpty
31 ADT Heap's Array-Based Implementation public class Heap { private int MAX_HEAP =100; private KeyedItem [] items; // array of heap items private int size; // number of heap items public Heap () { items = new KeyedItem [MAX_HEAP]; size =0; } public bool heapIsEmpty() { return size == 0; } // end heapIsEmpty
32 ADT Heap's Array-Based Implementation public void heapInsert(KeyItem newItem) throw HeapException // Method: Inserts the new item after the last item in the heap and trickles it up to // its proper position. The heap is full when it contains MAX_HEAP items. { if (size >= MAX_HEAP) throw HeapException("HeapException: Heap full"); // place the new item at the end of the heap items[size] = newItem; // trickle new item up to its proper position int place = size; int parent = (place - 1)/2; while ( (parent >= 0) && (items[place].getKey().compareTo( items[parent].getKey()) )>0) { // swap items[place] and items[parent] KeyedItem temp = items[parent]; items[parent] = items[place]; items[place] = temp; place = parent; parent = (place - 1)/2; } // end while ++size; } // end heapInsert
33 ADT Heap's Array-Based Implementation public KeyedItem heapDelete() // delete the item in the root of a heap { KeyedItem rootItem=null; if (!heapIsEmpty()) { rootItem = items[0]; items[0] = items[--size]; heapRebuild(0); } // end if return rootItem; } // end heapDelete
34 ADT Heap's Array-Based Implementation protected void heapRebuild(int root) { // if the root is not a leaf and the root's search key is less than the larger // of the search keys in the root's children int child = 2 * root + 1; // index of root's left child, if any if ( child < size ) { // root is not a leaf, so it has a left child at child int rightChild = child + 1; // index of right child, if any // if root has a right child, find larger child if ( (rightChild 0) child = rightChild; // index of larger child // if the root's value is smaller than the value in the larger child, swap values if ( items[root].getKey().compareTo( items[child].getKey())<0 ) { KeyedItem temp = items[root]; items[root] = items[child]; items[child] = temp; // transform the new subtree into a heap heapRebuild(child); } // end if // if root is a leaf, do nothing } // end heapRebuild // End of implementation file.
35 ADT Priority Queue's Heap Implementation Priority queue operations are analog to heap operations (how?) Priority value in a priority queue corresponds to heap item's search key Priority queue implementation can reuse the heap class If you know the maximum number of items in the priority queue, the heap is a better implementation Heap is always balanced
36 ADT Priority Queue's Heap Implementation class PriorityQueue { private Heap h; public PriorityQueue () { h= new Heap (); } public boolean pqIsEmpty() { return h.heapIsEmpty(); } // end pqIsEmpty
37 ADT Priority Queue's Heap Implementation class PriorityQueue { private Heap h; public PriorityQueue () { h= new Heap (); } public boolean pqIsEmpty() { return h.heapIsEmpty(); } // end pqIsEmpty
38 ADT Priority Queue's Heap Implementation public void pqInsert(KeyedItem newItem) throws PQueueException { try { h.heapInsert(newItem); } catch (HeapException e) { throw new PQueueException( "PQueueException: Priority queue full"); } // end catch } // end pqInsert void KeyedItem pqDelete() { return h.heapDelete(priorityItem); } // end pqDelete }// End of implementation file.
39 ADT Priority Queue's Heap Implementation public void pqInsert(KeyedItem newItem) throws PQueueException { try { h.heapInsert(newItem); } catch (HeapException e) { throw new PQueueException( "PQueueException: Priority queue full"); } // end catch } // end pqInsert void KeyedItem pqDelete() { return h.heapDelete(priorityItem); } // end pqDelete }// End of implementation file.
40 Heap-Sort A heap is used to sort an array of items Idea: 1. First transform the array into a heap 2. The array is partitioned into two regions - the Heap region and the Sorted region 3. Delete the root from the heap 4. Move the root from the heap region to the sorted region 5. Rebuild the heap 6. Repeat From step 3
41 Heap-Sort Original array: 1. Transform array into a heap: Store into a balance BT Call heapRebuild on the leaves from right to left
42 Heap-Sort 2. Partition array into two regions Heap region and sorted region
43 Heap-Sort 3. Delete root from heap
44 Heap-Sort 4. Move root from heap to sorted region Heap regionSorted region
45 Heap-Sort 5. Rebuild the heap
46 Heap-Sort 6. Repeat From step 3, Heap region Sorted region
47 Review A heap in which the root contains the item with the largest search key is called a ______. minheap maxheap complete heap binary heap
48 Review A heap in which the root contains the item with the smallest search key is called a ______. minheap maxheap complete heap binary heap
49 Review A heap is a ______. general tree table full binary tree complete binary tree
50 Review A semiheap is a ______. table complete binary tree general tree full binary tree
51 Review In an array-based implementation of a heap, the number of array items that must be swapped to transform a semiheap of n nodes into a heap is ______. n n + 1 log 2 n log 2 (n + 1)
52 Review In an array-based implementation of a heap, the heapDelete operation is ______. O(1) O(n) O(n 2 ) O(log n)
53 Review In an array-based implementation of a heap, the parent of the node in items[i] is always stored in ______. items[i/2] items[(i-1)/2] items[i-2] items[(i-2)/2]
54 Review In an array-based implementation of a heap, the heapInsert operation is ______. O(1) O(n) O(n 2 ) O(log n)
55 Review The heapsort is ______ in the worst case. O(n) O(log n) O(n * log n) O(n 2 )
56 Review The heapsort is ______ in the average case. O(1) O(n) O(log n) O(n * log n)
57 Review Which of the following is true about the heapsort? the heapsort does not require a second array the heapsort is more efficient than the mergesort in the worst case the heapsort is more efficient than the mergesort in the average case the heapsort is better than the quicksort in the average case