1 Priority Queues (Heaps)  Sections 6.1 to 6.5. 2 Priority Queues  Regular queues which supports –First In, First Out –Enqueue(): add a new element.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
Advertisements

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.
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.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture24.
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.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Priority Queues  Queues: first-in first-out in printer schedule  Disadvantage: short job, important job need to wait  Priority queue is a data structure.
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.
Dr. Andrew Wallace PhD BEng(hons) EurIng
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
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.
Cpt S 223 – Advanced Data Structures Priority Queues
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues (Heaps)
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Binary Heaps Text Read Weiss, § Binary Heap One-array representation of a tree Complete trees Building a Binary Heap Insert Delete.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
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.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
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.
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
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)
Partially Ordered Data ,Heap,Binary Heap
CS 201 Data Structures and Algorithms
Heaps (8.3) CSE 2011 Winter May 2018.
CSCE 210 Data Structures and Algorithms
Priority Queues (Heaps)
Source: Muangsin / Weiss
Binary Heaps What is a Binary Heap?
Heaps, Heap Sort, and Priority Queues
Priority Queues (Heaps)
Priority Queues Sections 6.1 to 6.5.
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CSCI2100 Data Structures Tutorial 7
Heaps, Heap Sort, and Priority Queues
CMSC 341: Data Structures Priority Queues – Binary Heaps
Trees 1: Theory, Models, Generic Heap Algorithms, Priority Queues
Binary Heaps Text Binary Heap Building a Binary Heap
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
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
Priority Queues & Heaps
Heap code in C++ template <class eType>
Sorting Dr. Yingwu Zhu.
Priority Queues (Heaps)
Chapter 9 The Priority Queue ADT
Data Structures for Shaping and Scheduling
Heaps & Multi-way Search Trees
Priority Queues Binary Heaps
Priority Queues (Heaps)
Presentation transcript:

1 Priority Queues (Heaps)  Sections 6.1 to 6.5

2 Priority Queues  Regular queues which supports –First In, First Out –Enqueue(): add a new element –Dequeue(): remove oldest element in queue  Data structure supports –Insert(): add a new element –deleteMin(): delete minimum element in priority queue

3 Applications of Priority Queues  In Operating Systems –Shortest Job First process scheduling  In Simulators –Scheduling the next event (smallest event time)  In essence –Any event/job management that assign priority to events/jobs

4 Priority Queue Implementation  Implemented as adaptor class around –Linked lists  O(N) worst-case time on either insert() or deleteMin() –Binary Search Trees  O(log(N)) average time on insert() and delete()  Overkill: all elements are sorted, –However, we only need the minimum element –Heaps  This is what we’ll study and use to implement Priority Queues  O(logN) worst case for both insertion and delete operations

5 Partially Ordered Trees  A partially ordered tree (POT) is a tree T such that: –There is an order relation <= defined for the vertices of T –For any vertex p and any child c of p, p <= c  Consequences: –The smallest element in a POT is the root –No conclusion can be drawn about the order of children

6 Binary Heaps  A binary heap is a partially ordered complete binary tree. –The tree is completely filled on all levels except possibly the lowest.  In a more general d-Heap –A parent node can have d children  We simply refer to binary heaps as heaps root

7 Vector Representation of Complete Binary Tree  Storing elements in vector in level-order –Parent of v[k] = v[k/2] –Left child of v[k] = v[2*k] –Right child of v[k] = v[2*k + 1] R lr lllrrrrl root rrrllrllrlR

8 Heap example  Parent of v[k] = v[k/2]  Left child of v[k] = v[2*k]  Right child of v[k] = v[2*k + 1]

9 Examples Which one is a heap?

10 Implementation of Priority Queue (heap)

11 Basic Heap Operations: insert(x)  Create a hole at next leaf (empty)  // Repair upward  Repeat –Locate parent –if POT not satisfied (should x inserted in the hole)  Sliding parent element to hole –else  Stop  Insert x into hole

12 Insertion Example: insert(14) (1) (2) (3) (4)

Implementation of insert /** * Insert item x, allowing duplicates. */ void insert( const Comparable & x ) { if( currentSize == array.size( ) - 1 ) array.resize( array.size( ) * 2 ); // Percolate up int hole = ++currentSize; Comparable copy = x; array[ 0 ] = std::move( copy );// for terminating the following loop for( ; x < array[ hole / 2 ]; hole /= 2 ) array[ hole ] = std::move( array[ hole / 2 ] ); array[ hole ] = std::move( array[ 0 ] ); } 13

14 Basic Heap Operations: deleteMin()  Delete the root element  // root becomes a hole  // Must move last element (last leaf) to somewhere  Let y be the last element (rightmost leaf node)  Repeat –find the smaller child of the hole –if POT not satisfied (should y inserted in hole)  Sliding smaller child into hole –else  Stop  Insert y into hole

15 deleteMin() example

16 deleteMin() Example (Cont’d)

Implementation of deleteMin() / * Remove the minimum item. * Throws UnderflowException if empty. */ void deleteMin( ) { if( isEmpty( ) ) throw UnderflowException{ }; array[ 1 ] = std::move( array[ currentSize-- ] ); percolateDown( 1 ); } / * Remove the minimum item and place it in minItem. * Throws Underflow if empty. */ void deleteMin( Comparable & minItem ) { if( isEmpty( ) ) throw UnderflowException{ }; minItem = std::move( array[ 1 ] ); array[ 1 ] = std::move( array[ currentSize-- ] ); percolateDown( 1 ); } 17

Implementation of deleteMin() /** * Internal method to percolate down in the heap. * hole is the index at which the percolate begins. */ void percolateDown( int hole ) { int child; Comparable tmp = std::move( 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 ] = std::move( array[ child ] ); else break; } array[ hole ] = std::move( tmp ); } 18

19 Constructor  Construct heap from a collection of item  How to? –Naïve methods –Insert() each element –Worst-case time: O(N(logN)) –We show an approach taking O(N) worst-case  Basic idea –First insert all elements into the tree without worrying about POT –Then, adjust the tree to satisfy POT

20 Constructor

21 Example percolateDown(7) percolateDown(6)percolateDown(5)

22 percolateDown(1) percolateDown(4)percolateDown(3) percolateDown(2)

23 C++ STL Priority Queues  priority_queue class template –Implements deleteMax instead of deleteMin in default –MaxHeap instead of MinHeap  Template –Item type –container type (default vector) –comparator (default less)  Associative queue operations –Void push(t) –void pop() –T& top() –void clear() –bool empty()

24 #include using namespace std; // Empty the priority queue and print its contents. template void dumpContents( const string & msg, PriorityQueue & pq ) { cout << msg << ":" << endl; while( !pq.empty( ) ) { cout << pq.top( ) << endl; pq.pop( ); } // Do some inserts and removes (done in dumpContents). int main( ) { priority_queue maxPQ; priority_queue,greater > minPQ; minPQ.push( 4 ); minPQ.push( 3 ); minPQ.push( 5 ); maxPQ.push( 4 ); maxPQ.push( 3 ); maxPQ.push( 5 ); dumpContents( "minPQ", minPQ ); dumpContents( "maxPQ", maxPQ ); return 0; }

25 Reading Assignment  Chapter 7