CMSC 341 Lecture 14: Priority Queues, Heaps

Similar documents
CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

CMSC 341. Binary Heaps. Priority Queues

Heaps, Heap Sort, and Priority Queues.

CMSC 341 Lecture 15 Leftist Heaps

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

CMSC 341 Lecture 15 Leftist Heaps

CS350: Data Structures Heaps and Priority Queues

CMSC 341 Leftist Heaps

Algorithms and Data Structures

Data Structures and Algorithms

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

Binary Heaps. CSE 373 Data Structures Lecture 11

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

Priority Queues (Heaps)

CE 221 Data Structures and Algorithms

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

CSCI2100B Data Structures Heaps

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

Priority Queues Heaps Heapsort

Priority Queues (Heaps)

CSE 332: Data Structures & Parallelism Lecture 3: Priority Queues. Ruth Anderson Winter 2019

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Recall: Properties of B-Trees

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

Implementations. Priority Queues. Heaps and Heap Order. The Insert Operation CS206 CS206

COMP : Trees. COMP20012 Trees 219

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

CSE 373: Data Structures and Algorithms

Binary Trees, Binary Search Trees

Data Structures and Algorithms for Engineers

9. Heap : Priority Queue

Priority Queues. Binary Heaps

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

Priority Queues Heaps Heapsort

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Figure 1: A complete binary tree.

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

The priority is indicated by a number, the lower the number - the higher the priority.

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

CSCI Trees. Mark Redekopp David Kempe

CS 315 April 1. Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin. algoritms for decrasekey increasekey Build-heap

Heaps. Heaps Priority Queue Revisit HeapSort

COMP 103 RECAP-TODAY. Priority Queues and Heaps. Queues and Priority Queues 3 Queues: Oldest out first

Binary heaps (chapters ) Leftist heaps

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

CMSC 341 Lecture 10 Binary Search Trees

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II

Priority Queues. 04/10/03 Lecture 22 1

CSE 214 Computer Science II Heaps and Priority Queues

Sorting and Searching

Basic Data Structures (Version 7) Name:

Data Structures Lesson 9

The smallest element is the first one removed. (You could also define a largest-first-out priority queue)

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Announcements. Problem Set 2 is out today! Due Tuesday (Oct 13) More challenging so start early!

COSC160: Data Structures Heaps. Jeremy Bolton, PhD Assistant Teaching Professor

Sorting and Searching

Administration CSE 326: Data Structures

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Priority Queues and Heaps. Heaps of fun, for everyone!

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

Collection of priority-job pairs; priorities are comparable.

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1.

CSE332: Data Abstractions Lecture 4: Priority Queues; Heaps. James Fogarty Winter 2012

Trees. A tree is a directed graph with the property

CSE373: Data Structures & Algorithms Priority Queues

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

Tables, Priority Queues, Heaps

Data Structures and Algorithms

CmpSci 187: Programming with Data Structures Spring 2015

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Nicki Dell Spring 2014

Figure 1: A complete binary tree.

Heaps. Heaps. A heap is a complete binary tree.

CS S-08 Priority Queues Heaps 1

CS 361 Data Structures & Algs Lecture 9. Prof. Tom Hayes University of New Mexico

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

Lecture 13: AVL Trees and Binary Heaps

Algorithms and Data Structures

CS106X Programming Abstractions in C++ Dr. Cynthia Bailey Lee

Programming II (CS300)

Course Review. Cpt S 223 Fall 2009

Chapter 9. Priority Queue

Fall, 2015 Prof. Jungkeun Park

Trees. (Trees) Data Structures and Programming Spring / 28

Module 2: Priority Queues

Lecture Notes on Priority Queues

Module 2: Priority Queues

Priority Queues and Binary Heaps

Heap Model. specialized queue required heap (priority queue) provides at least

Learning Goals. CS221: Algorithms and Data Structures Lecture #3 Mind Your Priority Queues. Today s Outline. Back to Queues. Priority Queue ADT

Overview of Presentation. Heapsort. Heap Properties. What is Heap? Building a Heap. Two Basic Procedure on Heap

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Programming Abstractions

Hash Tables. CS 311 Data Structures and Algorithms Lecture Slides. Wednesday, April 22, Glenn G. Chappell

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater

Module 2: Priority Queues

Transcription:

CMSC 341 Lecture 14: Priority Queues, Heaps Prof. John Park Based on slides from previous iterations of this course

Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues: Lists BSTs Heaps Heaps Properties Insertion Deletion UMBC CMSC 341 Priority Queues (Heaps) 2

Priority Queues and Heaps 3

Priority Queue ADT A priority queue stores a collection of entries Typically, an entry is a pair (key, value) where the key indicates the priority Smaller value, higher priority Keys in a priority queue can be arbitrary objects on which an order is defined UMBC CMSC 341 Priority Queues (Heaps) 4

Priority Queue vs Queue Priority queue is a specific type of queue Queues are FIFO The element in the queue for the longest time is the first one we take out Priority queues: most important, first out The element in the priority queue with the highest priority is the first one we take out Examples: emergency rooms, airline boarding UMBC CMSC 341 Priority Queues (Heaps) 5

Implementing Priority Queues Priority queues are an Abstract Data Type They are a concept, and hence there are many different ways to implement them Possible implementations include A sorted list An ordinary BST A balanced BST Run time will vary based on implementation UMBC CMSC 341 Priority Queues (Heaps) 6

Implementing a Priority Queue 7

Priority Queue: Unsorted List We can implement a priority queue with a simple unsorted list (array, vector, etc.) Insertion just adds element to end of list Enqueuing new element takes O(1) time However, to find the highest priority, must find MIN(entire list), which takes O(n) time UMBC CMSC 341 Priority Queues (Heaps) 8

Priority Queue: Sorted List We can implement a priority queue with a sorted list (array, vector, etc.) Sorted by priority upon insertion To find the highest priority, simply take the first element, in O(1) time findmin() --> list.front() Insertion can take O(n) time, however UMBC CMSC 341 Priority Queues (Heaps) 9

Priority Queue: BST A BST makes a bit more sense than a list Sorted like a regular BST upon insertion To find the minimum, just go to the left call findmin() And removal will be easy, because it will always be a leaf node! Insertion should take no more than O(log n) time call Insert() UMBC CMSC 341 Priority Queues (Heaps) 10

Priority Queue: BST Downsides Unfortunately, a BST Priority Queue can become unbalanced very easily, and the actual run time will suffer If we have a low priority (high value) instance as our root, nearly everything will be to its left findmin() is now O(n) time UMBC CMSC 341 Priority Queues (Heaps) 11

Priority Queue: Heap The most common way to implement a priority queue is using a heap A heap is a binary tree (not a BST!!!) that satisfies the heap condition : Nodes in the tree are sorted based in relation to their parent s value, such that if A is a parent node of B, then the key of node A is ordered with respect to the key of node B with the same ordering applying across the heap Additionally, the tree must be complete UMBC CMSC 341 Priority Queues (Heaps) 12

Heaps 13

Min Binary Heap A min binary heap is a Complete binary tree Neither child is smaller than the value in the parent No order between left and right In other words, smaller items go above larger ones UMBC CMSC 341 Priority Queues (Heaps) 14

Min Binary Heap This property is called a partial ordering There is no set relation between siblings, cousins, etc. only that the values grow as we increase our distance from the root As a result of this partial ordering, every path from the root to a leaf visits nodes in a non-decreasing order UMBC CMSC 341 Priority Queues (Heaps) 15

Min Binary Heap Performance Performance (n is the number of elements in the heap) construction O( n ) findmin() O( 1 ) insert() O( lg n ) deletemin() O( lg n ) UMBC CMSC 341 Priority Queues (Heaps) 16

Convert a Heap to an Array Level-order traversal UMBC CMSC 341 Priority Queues (Heaps) 17

Min Binary Heap Performance Heap efficiency results, in part, from the implementation Conceptually a complete binary tree But implemented by using an array/vector (in level order) with the root at index 1 UMBC CMSC 341 Priority Queues (Heaps) 18

Min Binary Heap Performance For a node at index i Its left child is at index 2i Its right child is at index 2i+1 Its parent is at index i/2 No pointer storage Fast computation of 2i and i/2 by bit shifting i << 1 = 2i i >> 1 = i/2 UMBC CMSC 341 Priority Queues (Heaps) 19

Min Binary Heap: Exercises How to find the parent of E? The left child of D? The right child of A? UMBC CMSC 341 Priority Queues (Heaps) 20

Building a Heap 21

Insert Operation Must maintain Heap shape: Easy, just insert new element at the end of the array Min heap order: 1. Could be wrong after insertion if new element is smaller than its ancestors 2. Continuously swap the new element with its parent until parent is not greater than it ( percolate up ) Performance of insert is O(log n) in the worst case because the height of a complete binary tree (CBT) is at most log n UMBC CMSC 341 Priority Queues (Heaps) 22

Insert Code void insert(const Comparable &x) { /* First, check we are not overflowing array (code not included here) */ } // percolate up Comparable tmp; int hole = ++currentsize; array[hole] = x; for( ; hole > 1 && x < array[hole/2]; hole /= 2) { // swap, from child to parent tmp = array[hole]; array[hole] = array[hole / 2]; array[hole / 2] = tmp; } UMBC CMSC 341 Priority Queues (Heaps) 23

Insert Code (v2) /* More efficient version, where instead of swapping pairs, we just shift values down until right spot */ void insert(const Comparable &x) { /* First check we are not overflowing array (code not included here) */ } // percolate up int hole = ++currentsize; for( ; hole > 1 && x < array[hole/2]; hole /= 2) { // swap, from child to parent array[hole] = array[hole / 2]; } array[hole] = x; UMBC CMSC 341 Priority Queues (Heaps) 24

Insert Example: 14 UMBC CMSC 341 Priority Queues (Heaps) 25

Delete Operation Steps Remove min element (the root) Maintain heap shape Maintain min heap order To maintain heap shape, actual node removed is last one in the array Replace root value with value from last node and delete last node Sift-down the new root value Continually exchange value with the smaller child until no child is smaller. UMBC CMSC 341 Priority Queues (Heaps) 26

Delete Code void deletemin() { /* First, check for empty queue (code not included here) */ int hole, child; Comparable tmp = array[currentsize--]; } for (hole = 1, child = 2; child <= currentsize; hole = child, child *= 2) { /* find smaller of siblings (if there is one) */ if (child < currentsize && array[child+1] < array[child]) child++; if (array[child] < tmp) array[hole] = array[child]; else break; } array[hole] = tmp; UMBC CMSC 341 Priority Queues (Heaps) 27

Example: Delete Min UMBC CMSC 341 Priority Queues (Heaps) 28

Example: Delete Min UMBC CMSC 341 Priority Queues (Heaps) 29

Visualization This visualization of a minimum heap may be helpful in your understanding of the different properties of a heap, as well as the exact steps taken for the operations of insertion, deletion, etc. http://www.cs.usfca.edu/~galles/javascriptvis ual/heap.html UMBC CMSC 341 Priority Queues (Heaps) 30