PRIORITY QUEUES AND HEAPS

Similar documents
PRIORITY QUEUES AND HEAPS

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

Announcements HEAPS & PRIORITY QUEUES. Abstract vs concrete data structures. Concrete data structures. Abstract data structures

HEAPS & PRIORITY QUEUES

PRIORITY QUEUES AND HEAPS

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

Programming II (CS300)

Algorithms and Data Structures

cs2010: algorithms and data structures

CSE 2123: Collections: Priority Queues. Jeremy Morris

Binary Search Trees. BinaryTree<E> Class (cont.) Section /27/2017

Programming II (CS300)

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

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

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

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

CS350: Data Structures Heaps and Priority Queues

The heap is essentially an array-based binary tree with either the biggest or smallest element at the root.

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

Course Review. Cpt S 223 Fall 2009

Recitation 9. Prelim Review

Priority Queues (Heaps)

Priority Queues Heaps Heapsort

CSE 241 Class 17. Jeremy Buhler. October 28, Ordered collections supported both, plus total ordering operations (pred and succ)

CompSci 201 Tree Traversals & Heaps

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

ext Total Score /20 /20 /15 /20 /25 /5 Grader

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF.

Lecture 17 Notes Priority Queues

EXAMINATIONS 2016 TRIMESTER 2

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

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

Lecture 17 Priority Queues

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

Data Structures Question Bank Multiple Choice

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

Priority queues. Priority queues. Priority queue operations

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

Name CPTR246 Spring '17 (100 total points) Exam 3

Containers: Priority Queues. Jordi Cortadella and Jordi Petit Department of Computer Science

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

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

Containers: Priority Queues

- Alan Perlis. Topic 24 Heaps

CS24 Week 8 Lecture 1

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

9. Heap : Priority Queue

Binary Heaps. CSE 373 Data Structures Lecture 11

Data Structures and Algorithms

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2017

Sorting and Searching

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

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT

COS 226 Midterm Exam, Spring 2009

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Binary Search Trees Treesort

Priority Queues. 04/10/03 Lecture 22 1

Priority Queues Heaps Heapsort

Programming II (CS300)

Course Review. Cpt S 223 Fall 2010

Sorting and Searching

So on the survey, someone mentioned they wanted to work on heaps, and someone else mentioned they wanted to work on balanced binary search trees.

Priority Queues (Heaps)

and 6.855J February 6, Data Structures

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

CS200 Spring 2004 Midterm Exam II April 14, Value Points a. 5 3b. 16 3c. 8 3d Total 100

Trees & Tree-Based Data Structures. Part 4: Heaps. Definition. Example. Properties. Example Min-Heap. Definition

Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Design and Analysis of Algorithms

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

CSE 214 Computer Science II Heaps and Priority Queues

COMP : Trees. COMP20012 Trees 219

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

CMSC 341 Lecture 14: Priority Queues, Heaps

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

COMP 103 Introduction to Data Structures and Algorithms

CE 221 Data Structures and Algorithms

Lecture Notes on Priority Queues

Standard ADTs. Lecture 19 CS2110 Summer 2009

Algorithms and Theory of Computation. Lecture 7: Priority Queue

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this

Recall: Properties of B-Trees

ASYMPTOTIC COMPLEXITY

Total Score /1 /20 /41 /15 /23 Grader

Prelim 2 Solution. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

CS165: Priority Queues, Heaps

Chapter 5 Data Structures Algorithm Theory WS 2016/17 Fabian Kuhn

CMPSCI 187: Programming With Data Structures. Review for Final Exam David Mix Barrington 10 December 2012

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

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

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

Lecture 23: Priority Queues, Part 2 10:00 AM, Mar 19, 2018

Priority Queues and Binary Heaps

Summer Final Exam Review Session August 5, 2009

Priority queues. Priority queues. Priority queue operations

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

182 review 1. Course Goals

Heaps, stacks, queues

Transcription:

PRIORITY QUEUES AND HEAPS Lecture 17 CS2110 Spring 201

Readings and Homework 2 Read Chapter 2 A Heap Implementation to learn about heaps Exercise: Salespeople often make matrices that show all the great features of their product that the competitor s product lacks. Try this for a heap versus a BST. First, try and sell someone on a BST: List some desirable properties of a BST that a heap lacks. Now be the heap salesperson: List some good things about heaps that a BST lacks. Can you think of situations where you would favor one over the other? With ZipUltra heaps, you ve got it made in the shade my friend!

Stacks and queues are restricted lists 3 Stack (LIFO) implemented as list add(), remove() from front of list (push and pop) Queue (FIFO) implemented as list add() on back of list, remove() from front of list These operations are O(1) Both efficiently implementable using a singly linked list with head and tail head 55 12 19 1 tail

Interface Bag (not In Java Collections) 4 interface Bag<E> implements Iterable { void add(e obj); } boolean contains(e obj); boolean remove(e obj); int size(); boolean isempty(); Iterator<E> iterator() Also called multiset Like a set except that a value can be in it more than once. Example: a bag of coins Refinements of Bag: Stack, Queue, PriorityQueue

Priority queue 5 Bag in which data items are Comparable Smaller elements (determined by compareto()) have higher priority remove() return the element with the highest priority = least element in the compareto() ordering break ties arbitrarily

Many uses of priority queues (& heaps) Surface simplification [Garland and Heckbert 1997] Event-driven simulation: customers in a line Collision detection: "next time of contact" for colliding bodies Graph searching: Dijkstra's algorithm, Prim's algorithm AI Path Planning: A* search Statistics: maintain largest M values in a sequence Operating systems: load balancing, interrupt handling Discrete optimization: bin packing, scheduling

java.util.priorityqueue<e> 7 interface PriorityQueue<E> { boolean add(e e) {...} //insert e. } void clear() {...} //remove all elems. E peek() {...} //return min elem. TIME log E poll() {...} //remove/return min elem. log boolean contains(e e) boolean remove(e e) int size() {...} Iterator<E> iterator() constant linear linear constant

Priority queues as lists 8 Maintain as unordered list add() put new element at front O(1) poll() must search the list O(n) peek() must search the list O(n) Maintain as ordered list add() must search the list O(n) poll() wamted element at top O(1) peek() O(1) Can we do better?

Heap 9 A heap is a concrete data structure that can be used to implement priority queues Gives better complexity than either ordered or unordered list implementation: add(): O(log n) (n is the size of the heap) poll(): O(log n) O(n log n) to process n elements Do not confuse with heap memory, where the Java virtual machine allocates space for objects different usage of the word heap

Heap: first property 10 Every element is >= its parent 4 14 21 8 19 35 22 38 55 10 20 Note: 19, 20 < 35: Smaller elements can be deeper in the tree!

Heap: second property: is complete, has no holes 11 Every level (except last) 4 completely filled. Nodes on bottom level 14 are as far left as possible. 21 8 19 35 22 38 55 10 20

Heap: Second property: has no holes 12 Not a heap because it has two holes 4 14 21 8 19 22 55 10 20 Not a heap because: missing nodes missing a node on level 2 bottom level nodes are not as far left as possible

Heap 13 Binary tree with data at each node Satisfies the Heap Order Invariant: 1. Every element is its parent. Binary tree is complete (no holes) 2. Every level (except last) completely filled. Nodes on bottom level are as far left as possible.

Numbering the nodes in a heap 14 Number node starting at 0 4 root in breadth-first left-right order 1 2 14 3 21 4 8 5 19 35 7 22 8 38 9 55 Children of node k are nodes 2k+1 and 2k+2 Parent of node k is node (k-1)/2

15 Can store a heap in an array b (could also be ArrayList or Vector) Heap nodes in b in order, going across each level from left to right, top to bottom Children of b[k] are b[2k + 1] and b[2k + 2] Parent of b[k] is b[(k 1)/2] 0 1 2 3 4 5 7 8 9 to parent to children Tree structure is implicit. No need for explicit links!

add(e) 1 4 14 21 8 19 35 22 38 55 10 20

add(e) 17 4 14 21 8 19 35 22 38 55 10 20 5 1. Put in the new element in a new node

add() 18 4 14 21 8 5 35 22 38 55 10 20 19 2. Bubble new element up if less than parent

add() 19 4 5 21 8 14 35 22 38 55 10 20 19 2. Bubble new element up if less than parent

add() 20 4 5 21 8 14 35 22 38 55 10 20 19

add() 21 4 5 21 8 14 35 22 38 55 10 20 19 2 1. Put in the new element in a new node

add() 22 4 5 21 8 14 2 22 38 55 10 20 19 35 2. Bubble new element up if less than parent

add() 23 4 2 21 8 14 5 22 38 55 10 20 19 35 2. Bubble new element up if less than parent

add() 24 2 4 21 8 14 5 22 38 55 10 20 19 35 2. Bubble new element up if less than parent

add() 25 2 4 21 8 14 5 22 38 55 10 20 19 35

add(e) 2 Add e at the end of the array Bubble e up until it no longer violateds heap order The heap invariant is maintained!

add() to a tree of size n 27 Time is O(log n), since the tree is balanced size of tree is exponential as a function of depth depth of tree is logarithmic as a function of size

add() --assuming there is space 28 /** An instance of a heap */ class Heap<E> { E[] b= new E[50]; // heap is b[0..n-1] int n= 0; // heap invariant is true } /** Add e to the heap */ public void add(e e) { b[n]= e; n= n + 1; bubbleup(n - 1); // given on next slide }

add(). Remember, heap is in b[0..n-1] 29 class Heap<E> { /** Bubble element #k up to its position. * Pre: heap inv holds except maybe for k */ private void bubbleup(int k) { int p= (k-1)/2; // inv: p is parent of k and every elmnt // except perhaps k is >= its parent while ( k > 0 && b[k].compareto(b[p]) < 0 ) { } } swap(b[k], b[p]); k= p; p= (k-1)/2;

poll() 30 4 5 21 8 14 35 22 38 55 10 20 19

poll() 31 4 5 21 8 14 35 22 38 55 10 20 19 1. Save top element in a local variable

poll() 32 4 5 21 8 14 35 22 38 55 10 20 19 2. Assign last value to the root, delete last value from heap

poll() 33 4 19 5 21 8 14 35 22 38 55 10 20 3. Bubble root value down

poll() 34 4 5 19 21 8 14 35 22 38 55 10 20 3. Bubble root value down

poll() 35 4 5 14 21 8 19 35 22 38 55 10 20 3. Bubble root value down

poll() 3 4 5 14 21 8 19 35 22 38 55 10 20 1. Save top element in a local variable

poll() 37 4 5 14 21 8 19 35 22 38 55 10 20 2. Assign last value to the root, delete last value from heap

poll() 38 4 5 14 21 8 19 35 22 38 55 10 20 2. Assign last value to the root, delete last value from heap

poll() 39 4 5 20 14 21 8 19 35 22 38 55 10 3. Bubble root value down

poll() 40 4 5 20 14 21 8 19 35 22 38 55 10 3. Bubble root value down

poll() 41 4 5 8 14 21 20 19 35 22 38 55 10 3. Bubble root value down

poll() 42 4 5 8 14 21 10 19 35 22 38 55 20

poll() 43 4 5 8 14 21 10 19 35 22 38 55 20 3. Bubble root value down

poll() 44 Remove and save the least element (at the root) This leaves a hole at the root Move last element of the heap to the root. Bubble element down always with smaller child, until heap invariant is true again. The heap invariant is maintained! Time is O(log n), since the tree is balanced

poll(). Remember, heap is in b[0..n-1] 45 /** Remove and return the smallest element * (return null if list is empty) */ public E poll() { } if (n == 0) return null; E v= b[0]; // smallest value at root. n= n 1; // move last b[0]= b[n]; // element to root bubbledown(0); return v;

c s smaller child 4 /** Tree has n node. * Return index of smaller child of node k (2k+2 if k >= n) */ public int smallerchild(int k, int n) { int c= 2*k + 2; // k s right child if (c >= n b[c-1].compareto(b[c]) < 0) c= c-1; return c; }

47 /** Bubble root down to its heap position. Pre: b[0..n-1] is a heap except maybe b[0] */ private void bubbledown() { int k= 0; int c= smallerchild(k, n); // inv: b[0..n-1] is a heap except maybe b[k] AND // b[c] is b[k] s smallest child while ( c < n && b[k].compareto(b[c]) > 0 ) { } } swap(b[k], b[c]); k= c; c= smallerchild(k, n);

Change heap behaviour a bit 48 Separate priority from value and do this: add(e, p); //add element e with priority p (a double) Be able to change priority change(e, p); //change priority of e to p THIS IS EASY! THIS IS HARD! Big question: How do we find e in the heap? Searching heap takes time proportional to its size! No good! Once found, change priority and bubble up or down. OKAY Assignment A: implement this heap! Use a second data structure to make change-priority expected log n time

HeapSort(b, n) Sort b[0..n-1] 49 Whet your appetite use heap to get exactly n log n in-place sorting algorithm. 2 steps, each is O(n log n) 1. Make b[0..n-1] into a max-heap (in place) 2. for (k= n-1; k > 0; k= k-1) { b[k]= poll i.e. take max element out of heap. } We ll post this algorithm on course website A max-heap has max value at root