Priority Queues Biary Heaps
Priority Queues Priority: some property of a object that allows it to be prioritized with respect to other objects of the same type Mi Priority Queue: homogeeous collectio of Comparables with the followig operatios (duplicates are allowed). Smaller value meas higher priority. q void isert (Comparable x) q void deletemi( ) q Comparable fidmi( ) q Costruct from a set of iitial values q boolea isempty( ) q boolea isfull( ) q void makeempty( )
Priority Queue Applicatios Priter maagemet: q The shorter documet o the priter queue, the higher its priority. Jobs queue withi a operatig system: q Users tasks are give priorities. System has high priority. Simulatios q The time a evet happes is its priority. Sortig (heap sort) q A elemets value is its priority.
Possible Implemetatios Use a sorted list. Sorted by priority upo isertio. q fidmi( ) --> list.frot( ) q isert( ) --> list.isert( ) q deletemi( ) --> list.erase( list.begi( ) ) Use ordiary BST q fidmi( ) --> tree.fidmi( ) q isert( ) --> tree.isert( ) q deletemi( ) --> tree.delete( tree.fidmi( ) ) Use balaced BST q guarateed O(lg ) for Red-Black
Mi Biary Heap A mi biary heap is a complete biary tree with the further property that at every ode either child is smaller tha the value i that ode (or equivaletly, both childre are at least as large as that ode). This property is called a partial orderig. As a result of this partial orderig, every path from the root to a leaf visits odes i a odecreasig order. What other properties of the Mi Biary Heap result from this property?
Mi Biary Heap Performace Performace ( is the umber of elemets i the heap) q costructio O( ) q fidmi O( 1 ) q isert O( lg ) q deletemi O( lg ) Heap efficiecy results, i part, from the implemetatio q Coceptually a complete biary tree q Implemetatio i a array/vector (i level order) with the root at idex 1
Mi Biary Heap Properties For a ode at idex i q its left child is at idex 2i q its right child is at idex 2i+1 q its paret is at idex ëi/2û No poiter storage Fast computatio of 2i ad ëi/2û by bit shiftig i << 1 = 2i i >> 1 = ëi/2û
Heap is a Complete Biary Tree
Which satisfies the properties of a Heap?
Mi BiaryHeap Defiitio public class BiaryHeap<AyType exteds Comparable<? super AyType>> { public BiaryHeap( ) { /* See olie code */ } public BiaryHeap( it capacity ){ /* See olie code */ } public BiaryHeap( AyType [ ] items ){/* Figure 6.14 */ } public void isert( AyType x ) { /* Figure 6.8 */ } public AyType fidmi( ) { /* TBD */ } public AyType deletemi( ) { /* Figure 6.12 */ } public boolea isempty( ) { /* See olie code */ } public void makeempty( ) { /* See olie code */ } private static fial it DEFAULT_CAPACITY = 10; private it curretsize; // Number of elemets i heap private AyType [ ] array; // The heap array } private void percolatedow( it hole ){/* Figure 6.12 */ } private void buildheap( ) { /* Figure 6.14 */ } private void elargearray(it ewsize){/* code olie */}
Mi BiaryHeap Implemetatio public AyType fidmi( ) { if ( isempty( ) ) throw Uderflow( ); retur array[1]; }
Isert Operatio Must maitai q CBT property (heap shape): Easy, just isert ew elemet at the ed of the array q Mi heap order Could be wrog after isertio if ew elemet is smaller tha its acestors Cotiuously swap the ew elemet with its paret util paret is ot greater tha it q Called sift up or percolate up Performace of isert is O( lg ) i the worst case because the height of a CBT is O( lg )
Mi BiaryHeap Isert (cot.) /** * Isert ito the priority queue, maitaiig heap order. * Duplicates are allowed. * @param x the item to isert. */ public void isert( AyType x ) { // resize array if eeded // place x ito the complete biary tree } // restore the heap order by percolatig up
Isert 14
Deletio Operatio Steps q Remove mi elemet (the root) q Maitai heap shape q Maitai mi heap order To maitai heap shape, actual ode removed is last oe i the array q Replace root value with value from last ode ad delete last ode q Sift-dow the ew root value Cotiually exchage value with the smaller child util o child is smaller.
Mi BiaryHeap Deletio(cot.) /** * Remove the smallest item from the priority queue. * @retur the smallest item, or throw UderflowExceptio, if empty. */ public AyType deletemi( ) { if( isempty( ) ) throw ew UderflowExceptio( ); AyType miitem = fidmi( ); array[ 1 ] = array[ curretsize-- ]; percolatedow( 1 ); } retur miitem;
MiBiaryHeap percolatedow(cot.) /** * Iteral method to percolate dow i the heap. * @param hole the idex at which the percolate begis. */ private void percolatedow( it hole ) { it child; AyType tmp = array[ hole ]; for( ; hole * 2 <= curretsize; hole = child ){ child = hole * 2; if( child!= curretsize && array[ child + 1 ].compareto( array[ child ] ) < 0 ) child++; if( array[ child ].compareto( tmp ) < 0 ) array[ hole ] = array[ child ]; else break; } array[ hole ] = tmp; }
deletemi
deletemi (cot.)
Costructig a Mi BiaryHeap A BH ca be costructed i O() time. Suppose we are give a array of objects i a arbitrary order. Sice it s a array with o holes, it s already a CBT. It ca be put ito heap order i O() time. q Create the array ad store elemets i it i arbitrary order. O() to copy all the objects. q Heapify the array startig i the middle ad workig your way up towards the root for (it idex = ë/2û ; idex > 0; idex--) percolatedow( idex );
Costructig a Mi BiaryHeap(cot.) //Costruct the biary heap give a array of items. public BiaryHeap( AyType [ ] items ){ curretsize = items.legth; } array = (AyType[]) ew Comparable[ (curretsize + 2)*11/10 ]; it i = 1; for( AyType item : items ) array[ i++ ] = item; buildheap( ); // Establish heap order property from a arbitrary // arragemet of items. Rus i liear time. private void buildheap( ){ for( it i = curretsize / 2; i > 0; i-- ) } percolatedow( i );
Performace of Costructio A CBT has 2 h-1 odes o level h-1. O level h-l, at most 1 swap is eeded per ode. O level h-2, at most 2 swaps are eeded. O level 0, at most h swaps are eeded. Number of swaps = S = 2 h *0 + 2 h-1 *1 + 2 h-2 *2 + + 2 0 *h = h å i= 0 i 2 ( h - i) = h = h(2 h+1-1) - ((h-1)2 h+1 +2) = 2 h+1 (h-(h-1))-h-2 = 2 h+1 -h-2 h å i= 0 2 i - h å i= 0 i2 i
Performace of Costructio (cot.) But 2 h+1 -h-2 = O(2 h ) But = 1 + 2 + 4 + + 2 h = Therefore, = O(2 h ) So S = O() h å i= 0 2 i A heap of odes ca be built i O() time.
Heap Sort Give values we ca sort them i place i O( log ) time q q q Isert values ito array -- O() heapify -- O() repeatedly delete mi -- O(lg ), times Usig a mi heap, this code sorts i reverse (high dow to low) order. With a max heap, it sorts i ormal (low up to high) order. Give a usorted array A[ ] of size for (i = -1; i >= 1; i--) { } x = fidmi( ); deletemi( ); A[i+1] = x;
Limitatios MiBiary heaps support isert, fidmi, deletemi, ad costruct efficietly. They do ot efficietly support the meld or merge operatio i which 2 BHs are merged ito oe. If H 1 ad H 2 are of size 1 ad 2, the the merge is i O( 1 + 2 ).
Leftist Mi Heap Supports q fidmi -- O( 1 ) q deletemi -- O( lg ) q isert -- O( lg ) q costruct -- O( ) q merge -- O( lg )
Leftist Tree The ull path legth, pl(x), of a ode, X, is defied as the legth of the shortest path from X to a ode without two childre (a o-full ode). Note that pl(null) = -1. A Leftist Tree is a biary tree i which at each ode X, the ull path legth of X s right child is ot larger tha the ull path legth of the X s left child. I.E. the legth of the path from X s right child to its earest o-full ode is ot larger tha the legth of the path from X s left child to its earest o-full ode. A importat property of leftist trees: q At every ode, the shortest path to a o-full ode is alog the rightmost path. Proof : Suppose this was ot true. The, at some ode the path o the left would be shorter tha the path o the right, violatig the leftist tree defiitio.
Leftist Mi Heap A leftist mi heap is a leftist tree i which the values i the odes obey heap order (the tree is partially ordered). Sice a LMH is ot ecessarily a CBT we do ot implemet it i a array. A explicit tree implemetatio is used. Operatios q fidmi -- retur root value, same as MBH q deletemi -- implemeted usig meld operatio q isert -- implemeted usig meld operatio q costruct -- implemeted usig meld operatio
Merge // Merge rhs ito the priority queue. // rhs becomes empty. rhs must be differet from this. // @param rhs the other leftist heap. public void merge( LeftistHeap<AyType> rhs ){ if( this == rhs ) retur; // Avoid aliasig problems root = merge( root, rhs.root ); rhs.root = ull; } // Iteral method to merge two roots. // Deals with deviat cases ad calls recursive merge1. private Node<AyType> merge(node<aytype> h1, Node<AyType> h2 ){ if( h1 == ull ) retur h2; if( h2 == ull ) retur h1; if( h1.elemet.compareto( h2.elemet ) < 0 ) retur merge1( h1, h2 ); else retur merge1( h2, h1 ); }
Merge (cot.) /** * Iteral method to merge two roots. * Assumes trees are ot empty, ad h1's root cotais smallest item. */ private Node<AyType> merge1( Node<AyType> h1, Node<AyType> h2 ) { if( h1.left == ull ) // Sigle ode h1.left = h2; // Other fields i h1 already accurate else { h1.right = merge( h1.right, h2 ); if( h1.left.pl < h1.right.pl ) swapchildre( h1 ); h1.pl = h1.right.pl + 1; } retur h1; }
Merge (cot.) Performace: O( lg ) q The rightmost path of each tree has at most ëlg(+1)û odes. So O( lg ) odes will be ivolved.
Studet Exercise Show the steps eeded to merge the Leftist Heaps below. The fial result is show o the ext slide. 6 8 17 12 10 15 19 20 30 25
Studet Exercise Fial Result 6 8 17 12 19 10 20 15 30 25
Mi Leftist Heap Operatios Other operatios implemeted usig Merge( ) q isert (item) Make item ito a 1-ode LH, X Merge(this, X) q deletemi Merge(left subtree, right subtree) q costruct from N items Make N LHs from the N values, oe elemet i each Merge each i q q oe at a time (simple, but slow) use queue ad build pairwise (complex but faster)
LH Costruct Algorithm: Make leftist heaps, H 1.H each with oe data value Istatiate Queue<LeftistHeap> q; for (i = 1; i <= ; i++) q.equeue(h i ); Leftist Heap h = q.dequeue( ); while (!q.isempty( ) ) q.equeue( merge( h, q.dequeue( ) ) ); h = q.dequeue( );