Heaps Priority Queues. 1/6/2016Data Structure: Heaps2 Outline Binary heaps Binomial queues Leftist heaps.

Slides:



Advertisements
Similar presentations
 Have to copy one array into another (N)
Advertisements

§6 Leftist Heaps CHAPTER 5 Graph Algorithms  Heap: Structure Property + Order Property Target : Speed up merging in O(N). Leftist Heap: Order Property.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
Chapter 6: Priority Queues (Heaps) Priority Queue ADT Heap Implementation CS 340 Page 100 Heap Applications Leftist Heaps.
COL 106 Shweta Agrawal and Amit Kumar
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Treaps.  Good (logarithmic) performance with random data  Linear performance if the data is sorted ◦ Solutions – Splay Trees Amortized O( lg n) performance.
Heaps, Heap Sort, and Priority Queues. Sorting III / Slide 2 Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Heaps, Heap Sort, and Priority Queues
Priority Queue (Heap) & Heapsort COMP171 Fall 2006 Lecture 11 & 12.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
© Haluk Bingöl v2.23 Data Structures and Algorithms - 03 Heaps and Priority Queues Dr. Haluk Bingöl BÜ - CmpE
Dijkstra/Prim 1 make-heap |V| insert |V| delete-min |E| decrease-key Priority Queues make-heap Operation insert find-min delete-min union decrease-key.
CS 315 Lecture 15 March 31 Goals Complete heap operations review insert, deletemin decreaseKey, increaseKey heap building Heap sorting Some applications.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on MinHeap: Insert Delete Converting an array.
CS 315 Lecture 18 Nov 15 Goals Complete heap operations review insert, deletemin decreaseKey, increaseKey heap building Heap sorting Some applications.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
0 Course Outline n Introduction and Algorithm Analysis (Ch. 2) n Hash Tables: dictionary data structure (Ch. 5) n Heaps: priority queue data structures.
CSE 326: Data Structures Binomial Queues Ben Lerner Summer 2007.
Princeton University COS 423 Theory of Algorithms Spring 2002 Kevin Wayne Binary and Binomial Heaps These lecture slides are adapted from CLRS, Chapters.
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
§3 Binary Heap 1. Structure Property: 【 Definition 】 A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
§8 Binomial Queues Haven’t we had enough about queues? What is a binomial queue for? Well, what is the average time for insertions with leftist or skew.
CS 146: Data Structures and Algorithms June 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
For Monday Read Weiss, chapter 7, sections 1-3. Homework –Weiss, chapter 4, exercise 6. Make sure you include parentheses where appropriate.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
WEEK 3 Leftist Heaps CE222 Dr. Senem Kumova Metin CE222_Dr. Senem Kumova Metin.
Cpt S 223 – Advanced Data Structures Priority Queues
1 Heaps (Priority Queues) You are given a set of items A[1..N] We want to find only the smallest or largest (highest priority) item quickly. Examples:
DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI.
Priority Queues (Heaps)
1 Binomial Tree Binomial tree. n Recursive definition: B k-1 B0B0 BkBk B0B0 B1B1 B2B2 B3B3 B4B4.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
CS223 Advanced Data Structures and Algorithms 1 Priority Queue and Binary Heap Neil Tang 02/09/2010.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Heaps A heap is a binary tree that satisfies the following properties: Structure property: It is a complete binary tree Heap-order property: Each node.
1 CSE 326: Data Structures Priority Queues (Heaps) Lecture 9: Monday, Jan 27, 2003.
Recitation Nov. 15. HW5: Huffman Encoding/Decoding Task: –Read a text file (i.e. “message.text”) and figure out character frequencies. Don’t forget ‘\n’
1 Priority Queues (Heaps)  Sections 6.1 to Priority Queues  Regular queues which supports –First In, First Out –Enqueue(): add a new element.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Heaps and Priority Queues What is a heap? A heap is a binary tree storing keys at its internal nodes and satisfying the following properties:
Heaps and Heap Sort. Sorting III / Slide 2 Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves)
CS 201 Data Structures and Algorithms
Priority Queues (Heaps)
Binary Heaps Priority Queues
Source: Muangsin / Weiss
CMSC 341 Lecture 13 Leftist Heaps
Heaps, Heap Sort, and Priority Queues
Priority Queues (Heaps)
Heaps, Heap Sort, and Priority Queues
Binary Heaps Priority Queues
CMSC 341 Lecture 14 Priority Queues & Heaps
BuildHeap The general algorithm is to place the N keys in an array and consider it to be an unordered binary tree. The following algorithm will build a.
Binary Heaps Priority Queues
CE 221 Data Structures and Algorithms
Heaps Priority Queues.
Heap code in C++ template <class eType>
Priority Queues (Heaps)
Tree.
Presentation transcript:

Heaps Priority Queues

1/6/2016Data Structure: Heaps2 Outline Binary heaps Binomial queues Leftist heaps

Binary Heaps

1/6/2016Data Structure: Heaps4 Heap order property For every root node N, the key in the parent of N is smaller than or equal to the key in N The smallest value is in the root.

1/6/2016Data Structure: Heaps5 Operations on priority queues Insert –Put an element into the queue DeleteMin –Find the minimal element –Return it –Remove it from the queue

1/6/2016Data Structure: Heaps6 Binary Heaps A binary heap is an implementation of a priority queue. A binary heap is a complete binary tree with heap order property.

1/6/2016Data Structure: Heaps7 Complete Binary Tree A binary tree is a complete binary tree if every level in the tree is completely filled, except the leaf level, which is filled from left to right Height is in  log 2 n , where n is the number of nodes.

1/6/2016Data Structure: Heaps8 Array implementation of complete binary tree A B D E I J K H C FG L ABCDIHGFEJ LK

1/6/2016Data Structure: Heaps9 Class BinaryHeap public class BinaryHeap {public BinaryHeap( ) {this( DEFAULT_CAPACITY ); } public BinaryHeap( int capacity ) {currentSize = 0; array = new Comparable[ capacity + 1 ]; } … private static final int DEFAULT_CAPACITY = 100; private int currentSize; // Number of elements in heap private Comparable [ ] array; // The heap array }

1/6/2016Data Structure: Heaps10 percolateUp

1/6/2016Data Structure: Heaps11 Method percolateUp private void percolateUp( int hole ) {Comparable x = array[hole]; while (hole > 1 && x.compareTo( array[ hole / 2 ] ) < 0) {array[ hole ] = array[ hole/2 ]; hole = hole/2; } array[ hole ] = x; }

1/6/2016Data Structure: Heaps12 Method percolateUp private void percolateUp( int hole ) {while (hole>1 && array[hole].compareTo( array[ hole/2 ])<0) {swap(hole, hole/2); hole = hole/2; } private void swap( int p1, int p2 ) {Comparable x = array[p1]; array[p1] = array[p2]; array[p2] = x; }

1/6/2016Data Structure: Heaps13 PercolateDown

1/6/2016Data Structure: Heaps14 Method percolateDown private void percolateDown( int hole ) {int child; while( hole * 2 <= currentSize) {child = hole * 2; if(child != currentSize&&array[ child+1].compareTo( array[child ])<0) child++;// choose the smaller child if( array[ child ].compareTo( array[ hole ] ) < 0 ) swap( hole, child ); else break; hole = child; }

1/6/2016Data Structure: Heaps15 Method percolateDown private void percolateDown( int hole ) {int child; Comparable tmp = array[ hole ]; // save the value of the node while ( hole * 2 <= currentSize ) {child = hole * 2; if(child != currentSize&&array[ child+1].compareTo( array[child ])<0) child++;// choose the smaller child if( array[ child ].compareTo( tmp ) < 0 ) {array[ hole ] = array[ child ];// move child up hole = child; // move hole down } else break; } array[ hole ] = tmp;// put the value in the hole }

1/6/2016Data Structure: Heaps16 Insertion

1/6/2016Data Structure: Heaps17 Method insert public void insert( Comparable x ) throws Overflow {if( isFull( ) )throw new Overflow( ); array[++currentSize]=x; percolateUp(currentSize); }

1/6/2016Data Structure: Heaps18 DeleteMin

1/6/2016Data Structure: Heaps19 Method deleteMin public Comparable findMin( ) {if( isEmpty( ) )return null; return array[ 1 ]; } public Comparable deleteMin( ) {if( isEmpty( ) )return null; Comparable minItem = findMin( ); array[ 1 ] = array[ currentSize--]; percolateDown( 1 ); return minItem; }

1/6/2016Data Structure: Heaps20 Method buildHeap private void buildHeap( ) {for( int i = currentSize / 2; i > 0; i-- ) percolateDown( i ); }

1/6/2016Data Structure: Heaps21 Method decreaseKey public void decreaseKey(int p, Comparable d) throws outOfRange {if( p>currentSize )throw new outOfRange(); array[ p ] = array[ p ] - d; percolateUp( p ); }

1/6/2016Data Structure: Heaps22 Method increaseKey public void increaseKey(int p, Comparable d) throws outOfRange {if( p>currentSize )throw new outOfRange(); array[ p ] = array[ p ] + d; percolateDown( p ); }

Binomial Queues

1/6/2016Data Structure: Heaps24 Binomial Tree A binomial tree is defined recursively as follow: A binomial tree of height 0, denoted by B 0, is a one- node tree. A binomial tree of height k, denoted by B k, is formed by attaching a binomial tree B k-1 to the root of another binomial tree B k-1.

1/6/2016Data Structure: Heaps25 Property of Binomial Trees A binomial tree of height k has 2 k nodes. The number of nodes at depth d is the binomial coefficient  k   d 

1/6/2016Data Structure: Heaps26 Structure A binomial queue is a collection of heap- ordered trees, each of which is a binomial tree

1/6/2016Data Structure: Heaps27 Binomial Nodes class BinomialNode {BinomialNode( Comparable theElement ) { this( theElement, null, null ); } BinomialNode( Comparable theElement, BinomialNode lt, BinomialNode nt ) {element = theElement; Child = lt;nextSibling = nt; } Comparable element; BinomialNode Child; BinomialNode nextSibling; }

1/6/2016Data Structure: Heaps28 Examples: binomial nodes Child nextSibling

1/6/2016Data Structure: Heaps29 Binomial Queues public class BinomialQueue {public BinomialQueue( ) {theTrees = new BinomialNode[ MAX_TREES ]; makeEmpty( );}... public void makeEmpty( ) {currentSize = 0; for( int i=0; i < theTrees.length; i++ ) theTrees[ i ] = null;} private static final int MAX_TREES = 14; private int currentSize; private BinomialNode [ ] theTrees; private int capacity( ) {return 2*theTrees.length - 1;} }

1/6/2016Data Structure: Heaps30 Method combineTrees private static BinomialNode combineTrees ( BinomialNode t1,BinomialNode t2 ) {if( t1.element.compareTo( t2.element ) > 0 ) return combineTrees( t2, t1 ); t2.nextSibling = t1.Child; t1.leftChild = t2; return t1; }

1/6/2016Data Structure: Heaps31 Method merge (1) public void merge( BinomialQueue rhs ) throws Overflow {if( this == rhs ) return; if( currentSize+rhs.currentSize>capacity() ) throw new Overflow( ); currentSize += rhs.currentSize; BinomialNode carry = null; for( int i=0,j=1; j<=currentSize; i++,j*=2 ) {BinomialNode t1 = theTrees[ i ]; BinomialNode t2 = rhs.theTrees[ i ];

1/6/2016Data Structure: Heaps32 Method merge (2) // No trees if (t1==null && t2==null && carry==null) {} // Only this if (t1!=null && t2==null && carry==null) {} // Only rhs if (t1==null && t2!=null && carry==null) {theTrees[i] = t2; rhs.theTrees[i] = null;} // Only carry if (t1==null && t2==null && carry!=null) {theTrees[ i ] = carry; carry = null;} // this & rhs if (t1!=null && t2==null && carry!=null) {carry = combineTrees( t1, t2 ); theTrees[i]=rhs.theTrees[i]=null;}

1/6/2016Data Structure: Heaps33 Method merge (3) // this and carry if (t1!=null && t2==null && carry!=null) {carry = combineTrees( t1, carry ); theTrees[ i ] = null;} // rhs and carry if (t1==null && t2!=null && carry!=null) {carry = combineTrees( t2, carry ); rhs.theTrees[ i ] = null;} // All three if (t1!=null && t2!=null && carry!=null) {theTrees[ i ] = carry; carry = combineTrees( t1, t2 ); rhs.theTrees[ i ] = null;} }

1/6/2016Data Structure: Heaps34 Method merge (4) for( int k=0; k < rhs.theTrees.length; k++ ) rhs.theTrees[ k ] = null; rhs.currentSize = 0; }

1/6/2016Data Structure: Heaps35 Method insert public void insert( Comparable x ) throws Overflow {BinomialQueue oneItem= new BinomialQueue( ); oneItem.currentSize = 1; oneItem.theTrees[0] = new BinomialNode( x ); merge( oneItem ); }

1/6/2016Data Structure: Heaps36 Method deleteMin (2) for( int j = minIndex - 1; j >= 0; j-- ) {deletedQueue.theTrees[ j ] = deletedTree; deletedTree = deletedTree.nextSibling; deletedQueue.theTrees[ j ].nextSibling = null; } theTrees[ minIndex ] = null; currentSize -= deletedQueue.currentSize + 1; try { merge( deletedQueue ); } catch( Overflow e ) { } return minItem; }

1/6/2016Data Structure: Heaps37 Method deleteMin public Comparable deleteMin( ) {if( isEmpty( ) )return null; int minIndex = findMinIndex( ); Comparable minItem = theTrees[minIndex].element; BinomialNode deletedTree = theTrees[ minIndex ].child; BinomialQueue deletedQueue = new BinomialQueue( ); deletedQueue.currentSize =(1 << minIndex)-1;

Leftist Heaps

1/6/2016Data Structure: Heaps39 Null Path Length The null path length of the node X, npl(X), is the length of the shortest path from X to a node without 2 children. npl(X) = 1 + min (npl(Y 1 ), npl(Y 2 )), where Y 1 and Y 2 are children of X

1/6/2016Data Structure: Heaps40 Leftist Trees A leftist tree is a binary tree such that for every node X in the tree npl(left)  npl(right), where left and right are left child and right child of X

1/6/2016Data Structure: Heaps41 Examples of leftist trees

1/6/2016Data Structure: Heaps42 Leftist Heap A leftist heap is a leftist tree with heap order property

1/6/2016Data Structure: Heaps43 Leftist Tree Nodes class LeftHeapNode {LeftHeapNode( Comparable theElement ) {this( theElement, null, null );} LeftHeapNode( Comparable theElement, LeftHeapNode lt, LeftHeapNode rt ) {element = theElement; npl = 0; left = lt;right = rt;} Comparable element; int npl; LeftHeapNode left;LeftHeapNode right; }

1/6/2016Data Structure: Heaps44 Merge Leftist Heaps

1/6/2016Data Structure: Heaps45 Merge Leftist Heaps

1/6/2016Data Structure: Heaps46 Merge Leftist Heaps

1/6/2016Data Structure: Heaps47 Method merge1 private static LeftHeapNode merge1 ( LeftHeapNode h1, LeftHeapNode h2 ) {if( h1.left == null ) // Single node h1.left = h2; // Other fields in h1 OK else {h1.right = merge( h1.right, h2 ); if( h1.left.npl < h1.right.npl ) swapChildren( h1 ); h1.npl = h1.right.npl + 1; } return h1; }

1/6/2016Data Structure: Heaps48 Method merge public void merge( LeftistHeap rhs ) {if( this == rhs ) return; root = merge( root, rhs.root ); rhs.root = null; } private static LeftHeapNode merge( LeftHeapNode h1, LeftHeapNode h2 ) {if( h1 == null ) return h2; if( h2 == null ) return h1; if( h1.element.compareTo( h2.element ) < 0 ) return merge1( h1, h2 ); else return merge1( h2, h1 ); }

1/6/2016Data Structure: Heaps49 Methods insert, deleteMIn public void insert( Comparable x ) {root=merge(new LeftHeapNode(x),root); } public Comparable deleteMin( ) {if( isEmpty( ) )return null; Comparable minItem = root.element; root = merge( root.left, root.right ); return minItem; }

1/6/2016Data Structure: Heaps50 Applications Event simulation Merge sort

1/6/2016Data Structure: Heaps51 Event Simulation Events have the scheduled time to happen. Advancing time by clock ticks is too slow. We need to find the “next” event. So, events are put into heaps with time as the element. We choose the next event from the root of the heapp.

1/6/2016Data Structure: Heaps52 Heap Sort

1/6/2016Data Structure: Heaps53 Heap Sort

1/6/2016Data Structure: Heaps54 Heap Sort

1/6/2016Data Structure: Heaps55 Heap Sort

1/6/2016Data Structure: Heaps56 Heap Sort

1/6/2016Data Structure: Heaps57