DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI.

Slides:



Advertisements
Similar presentations
§6 Leftist Heaps CHAPTER 5 Graph Algorithms  Heap: Structure Property + Order Property Target : Speed up merging in O(N). Leftist Heap: Order Property.
Advertisements

DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
COL 106 Shweta Agrawal and Amit Kumar
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
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.
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.
Priority Queues And the amazing binary heap Chapter 20 in DS&PS Chapter 6 in DS&AA.
1 6.3 Binary Heap - Other Heap Operations There is no way to find any particular key without a linear scan through the entire heap. However, if we know.
Heaps, Heap Sort, and Priority Queues
CSE332: Data Abstractions Lecture 5: Binary Heaps, Continued Tyler Robison Summer
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.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Priority queues CS310 – Data Structures Professor Roch Weiss, Chapter 6.9, 21 All figures marked with a chapter and section number are copyrighted © 2006.
Chapter 6: Priority Queues Priority Queues Binary Heaps Mark Allen Weiss: Data Structures and Algorithm Analysis in Java Lydia Sinapova, Simpson College.
Priority Queues  Queues: first-in first-out in printer schedule  Disadvantage: short job, important job need to wait  Priority queue is a data structure.
CS 315 Lecture 15 March 31 Goals Complete heap operations review insert, deletemin decreaseKey, increaseKey heap building Heap sorting Some applications.
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.
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.
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.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
CS 146: Data Structures and Algorithms June 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 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:
Priority Queues (Heaps)
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
CSE332: Data Abstractions Lecture 5: Binary Heaps, Continued Dan Grossman Spring 2012.
CS223 Advanced Data Structures and Algorithms 1 Priority Queue and Binary Heap Neil Tang 02/09/2010.
Heaps Priority Queues. 1/6/2016Data Structure: Heaps2 Outline Binary heaps Binomial queues Leftist heaps.
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.
1 CSE 326: Data Structures Priority Queues (Heaps) Lecture 9: Monday, Jan 27, 2003.
CSE 326: Data Structures Lecture #6 Putting Our Heaps Together Steve Wolfman Winter Quarter 2000.
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
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
Heaps (8.3) CSE 2011 Winter May 2018.
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
CMSC 341: Data Structures Priority Queues – Binary Heaps
Binary Heaps Priority Queues
CMSC 341 Lecture 14 Priority Queues & Heaps
Binary Heaps Priority Queues
CE 221 Data Structures and Algorithms
Heaps Priority Queues.
Heap code in C++ template <class eType>
Priority Queues (Heaps)
Priority Queues CSE 373 Data Structures.
Data Structures and Algorithm Analysis Priority Queues (Heaps)
Priority Queues Binary Heaps
Priority Queues (Heaps)
Presentation transcript:

DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI

2 ROAD MAP PRIORITY QUEUES (HEAPS) Model Simple Implementations Binary Heap Applications of Priority Queues d-Heaps Leftist Heaps

3 Model Priority Queue is a data structure that allows at least two operations insert equivalent to enqueue operation in queue ADT deleteMin finds, returns and removes the minimum element in priority queue equivalent to dequeue operation in queue ADT

4 Model

5 Many applications Printer queues Multiuser O/S process scheduling Many graph algorithms

6 How to Implement a Priority Queue Linked list Unsorted insertion takes O(1) time deletion takes O(N) time Sorted insertion takes O(N) time deletion takes O(1) time

7 How to Implement a Priority Queue Binary Search Tree Insertion and deletion takes O(logN) time Uses pointers Complicated Constant running time is large Supports more functions that are not necessary

8 How to Implement a Priority Queue Heap Does not use pointers N insertion takes O(N) time Insertion takes O(1) on amortize DeleteMin takes O(logN) Efficient merge of priority queues by using pointers

9 Heap Structures Binary Heap d-Heap Leftist Heap Binomial Heap Fibonacci Heap Binary heap is very common ! We will refer to binary heaps as “heaps” Heaps have 2 properties Structure property Heap-Order property

10 Structure Property of Heaps Binary heap is a complete binary tree completely filled except the bottom level which is filled from left to right if heap has height h then number of nodes is between 2 h and 2 h+1 -1 height of a heap with N nodes is O(logN) complete binary tree it is a regular structure so can be represented in an array !

11 Structure Property of Heaps For an element in position i 2i is the left child 2i+1 is the right child i/2 is the parent array implementation requires an estimate on max-size Array implementation of complete binary tree

12 Heap-Order Property For each node X, key in the parent is smaller than the key in X (except the root) Minimum element can always be found at the root Only left tree is a heap !

13 // class interface for priority queues template class BinaryHeap { public: explicit BinaryHeap( int capacity = 100 ); bool isEmpty( ) const; bool isFull( ) const; const Comparable & findMin( ) const; void insert( const Comparable & x ); void deleteMin( ); void deleteMin( Comparable & minItem ); void makeEmpty( ); private: int currentSize; // Number of elements in heap vector array; // The heap array void buildHeap( ); void percolateDown( int hole ); };

14 /* Construct the binary heap. template BinaryHeap ::BinaryHeap( int capacity ) : array( capacity + 1 ), currentSize( 0 ) { } /*Test if the priority queue is logically empty. template bool BinaryHeap ::isEmpty( ) const { return currentSize == 0; } /*Test if the priority queue is logically full. template bool BinaryHeap ::isFull( ) const { return currentSize == array.size( ) - 1; } /*Make the priority queue logically empty. template void BinaryHeap ::makeEmpty( ) { currentSize = 0;

15 Basic Heap Operations - insert Algorithm create a hole in the next available array position while inserting X in the hole violate heap order Percolate up the hole (by swapping with the parent) insert X in the hole

16 Example Attempt to insert 14 Creating a hole Bubbling the hole up

17 Example Remaining two steps to insert 14

18 Anaylsis of Insert Operation Analysis If the hole percolated up d levels run-time is O(d) In worst case O(logN) On average case O(1) comparisons

19 /* Insert item x into the priority queue template void BinaryHeap ::insert( const Comparable & x ) { if( isFull( ) ) throw Overflow( ); // Percolate up int hole = ++currentSize; for( ; hole > 1 && x < array[ hole / 2 ]; hole /= 2 ) array[ hole ] = array[ hole / 2 ]; array[ hole ] = x; }

20 Basic Heap Operations-deleteMin Algorithm Find the minimum (at the root) Remove the minimum  a hole is created at root While the last element X can not be inserted in the hole without violating the heap order Percolate down the hole  swap with smaller child Insert X into the hole Return minimum

21 Example Creation of the hole at the root First 13 is removed, and 31 is placed in the heap

22 Example Next two steps in deleteMin

23 Example Last two steps in deleteMin

24 Anaylsis of deleteMin Operation A path from root to an internal node is traced Run time = O(logN) in worst and average case

25 /* Remove the smallest item from the priority queue template void BinaryHeap ::deleteMin( Comparable & minItem ) { if( isEmpty( ) ) throw Underflow( ); minItem = array[ 1 ]; array[ 1 ] = array[ currentSize-- ]; percolateDown( 1 ); } /* Internal method to percolate down in the heap. template void BinaryHeap ::percolateDown( int hole ) { int child; Comparable tmp = array[ hole ]; for( ; hole * 2 <= currentSize; hole = child ) { child = hole * 2; if(child != currentSize && array[child + 1]<array[child] ) child++; if( array[ child ] < tmp )array[ hole ] = array[ child ]; elsebreak; } array[ hole ] = tmp; }

26 Other Heap Operations decreaseKey Percolate up the node increaseKey Percolate down the node remove Removes the node at position p from heap perform decreaseKey perform deleteMin buildHeap Insert N keys to an empty heap perform N insertions Worst case  O(NlogN) Average case  O(N) First build the structure and then put in heap order

27 Algorithm of buildHeap Operation /* Establish heap order property template void BinaryHeap ::buildHeap( ){ for( int i = currentSize / 2; i > 0; i-- ) percolateDown( i ); }

28 Example Left : initial heap; right: after percolateDown(7) Left : after percolateDown(6); right: after percolateDown(5)

29 Example Left : after percolateDown(4); right: after percolateDown(3) Left : after percolateDown(2); right: after percolateDown(1)

30 Sum of heights of the nodes Theorem : For the perfect binary tree of height h containing 2 h+1 -1 nodes, the sum of the heights of the nodes is 2 h+1 -1 –(h+1) Proof : Tree consist of 1 node at height h, 2 nodes at height h-1, 2 2 nodes at height h-2, in general 2 i nodes at height h-i

31 The sum of the heights of all the nodes is then Multiplying by 2 gives the equation If we subtract two equations

32 Applications of Priority Queues 1- Selection Problem input = N elements output = k th largest element Algorithm: read N elements in an array  O(n) buildHeap  O(n) perform k deleteMin  O(k logn) Total RunTime= O(n + k logn) if k = O(n/logn)  runtime = O(n) if k = Γn/2  runtime = O(n logn)

33 Applications of Priority Queues 2- Event Simulation Assume a bank with k tellers Customers arrive and wait until a teller available Customer arrival time and service time has a distribution function Problem : Use a simulation to determine number of tellers to ensure that the average customer wait is low. Events Customer arrival  use regular queue to determine next event Customer left  use priority queue to determine next event There are C customers  2C events Run time = O (c log k)

34 d-Heaps Nodes have at most d children Shallow  Insert  one comparison for each percolate Delete  d-1 comparisons Good when number of insertions are much greater than deletion

35 A 3-Heap

36 Leftist Heaps Support merge operation efficiently Merge  O(N) for binary heaps Using arrays θ(N) Efficient implementation Pointers makes others slower Leftist heap has both a structural property and an ordering property Its difference from binary heap is that, leftist heaps are not perfectly balanced

37 Leftist Heaps Definition : Null path length of a node x is the length of the shortest path from X to a node without two children. Only left tree is lefist heap

38 Theorem : A leftist tree with r nodes on the right path must have at least 2 r -1 nodes Proof by induction: –if r = 1, there must be at least one tree node. –otherwise, suppose that the theorem is true for 1,2,…,r. –consider a leftist tree with r+1 noes on the right path –then the root has a right subtree with r nodes on the right path, and a left subtree with at least r nodes on the right path (otherwise it would not be leftist) –applying in the inductive hypothesis to these subtrees yields a minimum of 2 r -1 nodes in each subtree –this plus the root gives at least 2 r+1 -1 nodes in the tree, prooving the theorem.

39 Leftist Heap Operations Fundamental operation on leftist heaps is “merging” Algorithm if H1 or H2 is NULL return the other one compare the root values (assume H1 is smaller) H1->right = Merge(H1->right, H2) swap the left and right subtrees if necessary if leftist heap property is violated update the Npl of the root of H1 return H1

40 Leftist Heap Operations Two leftist heaps H 1 and H 2

41 Leftist Heap Operations Result of merging H 2 and H 1 ’s right subheap

42 Leftist Heap Operations Result of attaching leftist heap of previous figure as H 1 ’s right child

43 Leftist Heap Operations Result swapping children of H 1 ’s root

44 Leftist Heap Operations Result of merging right paths of H 1 and H 2

45 template class LeftistNode { Comparable element; LeftistNode *left; LeftistNode *right; int npl; LeftistNode(const Comparable & theElement, LeftistNode *lt=NULL, LeftistNode *rt = NULL, int np=0 ) : element( theElement ), left( lt ), right( rt ), npl( np ) { } friend class LeftistHeap ; };

46 template class LeftistHeap { public: LeftistHeap( ); LeftistHeap( const LeftistHeap & rhs ); ~LeftistHeap( ); bool isEmpty( ) const; bool isFull( ) const; const Comparable & findMin( ) const; void insert( const Comparable & x ); void deleteMin( ); void deleteMin( Comparable & minItem ); void makeEmpty( ); void merge( LeftistHeap & rhs ); const LeftistHeap & operator=( const LeftistHeap & rhs );

47 private: LeftistNode *root; LeftistNode * merge( LeftistNode *h1, LeftistNode *h2 ) const; LeftistNode * merge1( LeftistNode *h1, LeftistNode *h2 ) const; void swapChildren( LeftistNode * t ) const; void reclaimMemory( LeftistNode * t ) const; LeftistNode * clone( LeftistNode *t ) const; };

48 /*Construct the leftist heap. template LeftistHeap ::LeftistHeap( ) { root = NULL; } /* Copy constructor. template LeftistHeap ::LeftistHeap( const LeftistHeap & rhs ) { root = NULL; *this = rhs; } /*Destruct the leftist heap. template LeftistHeap ::~LeftistHeap( ) { makeEmpty( ); }

49 /*Merge rhs into the priority queue. rhs becomes empty. rhs must be different from this. template void LeftistHeap ::merge( LeftistHeap & rhs ) { if( this == &rhs ) // Avoid aliasing problems return; root = merge( root, rhs.root ); rhs.root = NULL; } /*Internal method to merge two roots. template LeftistNode * LeftistHeap ::merge( LeftistNode * h1, LeftistNode * h2 ) const { if( h1 == NULL )return h2; if( h2 == NULL )return h1; if( h1->element element ) return merge1( h1, h2 ); else return merge1( h2, h1 ); }

50 /*Internal method to merge two roots. Assumes trees are not empty, and h1's root contains smallest item. template LeftistNode * LeftistHeap :: merge1( LeftistNode * h1, LeftistNode * h2 ) const { if( h1->left == NULL ) // Single node h1->left = h2; // Other fields in h1 already accurate else { h1->right = merge( h1->right, h2 ); if( h1->left->npl right->npl ) swapChildren( h1 ); h1->npl = h1->right->npl + 1; } return h1; }

51 /*Insert item x into the priority queue, maintaining heap order. template void LeftistHeap ::insert( const Comparable & x ) { root = merge( new LeftistNode ( x ), root ); } /* Remove the smallest item from the priority queue. template void LeftistHeap ::deleteMin( ) { if( isEmpty( ) ) throw Underflow( ); LeftistNode *oldRoot = root; root = merge( root->left, root->right ); delete oldRoot; }