CS 310: Priority Queues and Binary Heaps

Similar documents
CS 310: Priority Queues and Binary Heaps

Priority Queues Heaps Heapsort

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

Priority Queues Heaps Heapsort

CSE 373: Data Structures and Algorithms

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

CE 221 Data Structures and Algorithms

Data Structures and Algorithms

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

Heaps, Heap Sort, and Priority Queues.

Priority Queues (Heaps)

CS350: Data Structures Heaps and Priority Queues

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

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

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

CMSC 341 Lecture 14: Priority Queues, Heaps

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

Priority Queues (Heaps)

Exam Data structures DAT036/DAT037/DIT960

CS 310: Tree Rotations and AVL Trees

Course Review. Cpt S 223 Fall 2009

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

CS 315 Data Structures mid-term 2

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

CompSci 201 Tree Traversals & Heaps

Data Structures Lesson 9

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

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

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

Course Review for Finals. Cpt S 223 Fall 2008

COMP : Trees. COMP20012 Trees 219

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

Figure 1: A complete binary tree.

CSCI-1200 Data Structures Spring 2016 Lecture 22 Priority Queues, part II (& Functors)

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

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

CS102 Binary Search Trees

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect).

AMORTIZED ANALYSIS. Announcements. CSE 332 Data Abstractions: Priority Queues, Heaps, and a Small Town Barber. Today.

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Algorithms and Data Structures

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

Tables and Priority Queues

Adam Blank Lecture 3 Winter 2017 CSE 332. Data Structures and Parallelism

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

CSCI2100B Data Structures Heaps

Course Review. Cpt S 223 Fall 2010

CSE373 Fall 2013, Midterm Examination October 18, 2013

CSE373: Data Structures & Algorithms Priority Queues

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

Priority Queues. 04/10/03 Lecture 22 1

403: Algorithms and Data Structures. Heaps. Fall 2016 UAlbany Computer Science. Some slides borrowed by David Luebke

Recall: Properties of B-Trees

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

Data Structure. A way to store and organize data in order to support efficient insertions, queries, searches, updates, and deletions.

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues. Aaron Bauer Winter 2014

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

Figure 1: A complete binary tree.

Today s Outline. The One Page Cheat Sheet. Simplifying Recurrences. Set Notation. Set Notation. Priority Queues. O( 2 n ) O( n 3 )

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CS 361, Lecture 21. Outline. Things you can do. Things I will do. Evaluation Results

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

Data Structures and Algorithms

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

CS 2150 Final Exam, Spring 2018 Page 1 of 10 UVa userid:

CSC263 Week 2. Larry Zhang

Appendix A and B are also worth reading.

CS 315 Data Structures Spring 2012 Final examination Total Points: 80

Binary Heaps. CSE 373 Data Structures Lecture 11

Basic Data Structures and Heaps

Priority Queues and Heaps

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

CMSC 341. Binary Heaps. Priority Queues

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

Sorting and Searching

Binary Trees. Recursive definition. Is this a binary tree?

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

CSE 332, Spring 2010, Midterm Examination 30 April 2010

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

Final Examination CSE 100 UCSD (Practice)

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

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

COMP250: Priority queue ADT, Heaps. Lecture 23 Jérôme Waldispühl School of Computer Science McGill University

Programming II (CS300)

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

CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40%

Exam Data structures DIT960/DAT036

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

INF2220: algorithms and data structures Series 4

Exam Datastrukturer. DIT960 / DIT961, VT-18 Göteborgs Universitet, CSE

Binary Search Trees Treesort

Sorting and Searching

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

CS 240 Data Structures and Data Management. Module 2: Priority Queues

CSE 373 Autumn 2010: Midterm #2 (closed book, closed notes, NO calculators allowed)

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

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

CSE373 Winter 2014, Midterm Examination January 29, 2014

Transcription:

CS 310: Priority Queues and Binary Heaps Chris Kauffman Week 14-2

Priority Queues Queue What operations does a queue support? Priority: Number representing importance Convention lower is better priority Bring back life form. Priority One. All other priorities rescinded. Symmetric code if higher is better Priority Queue (PQ): Supports 3 operations void insert(t x,int p): Insert x with priority p T findmin(): Return the object with the best priority void deletemin(): Remove the the object with the best priority

Priority Explicit Priority insert(t x, int p) Priority is explicitly int p Separate from data Implicit Priority insert(comparable<t> x) x "knows" its own priority Comparisons dictated by x.compareto(y) Implicit is simpler for discussion: only one thing (x) to draw Explicit usually uses a wrapper node of sorts class PQElem<T> extends Comparable<PQElem>{ int priority; T elem; public int compareto(pqelem<t> that){ return this.priority - that.priority;

Exercise: Design a PQ Discuss How would you design PriorityQueue class? What underlying data structures would you use? Discuss with a neighbor Give rough idea of implementation Make it as efficient as possible in Big-O sense Must Implement Constructor void insert(t x): Insert x, knows its own priority, compare via x.compareto(y) T findmin(): Return the object with the best priority void deletemin(): Remove the the object with the best priority, re-arrange if needed

Exercise Results Priority Queue implementations based on existing data structures Data Structure insert(x) findmin() deletemin() Notes Sorted Array O(N) O(1) O(1) Keep min at high index Sorted Linked List O(N) O(1) O(1) Min at head or tail Binary Search Tree O(height) O(height) O(height) Min at left-most AVL or Red-Black Tree O(log N) O(log N) O(log N) Height log N Hash Table O(N) O(1) O(1) Tricky and pointless Questions Do priority queues implement more or less functionality than Binary Search Trees? Can we do better than these operational complexities?

Binary Heap: Sort of Sorted Most common way to build a PQ is using a new-ish data structure, the Binary Heap. Looks similar to a Binary Search Tree but maintains a different property BST Property A Node must be bigger than its left children and smaller than its right children Binary Min-Heap Property A Node must be smaller than its children

Heap and Not Heap Which of these is a min-heap and which is not?

Trees and Heaps in Arrays Mostly we have used trees of linked Nodes Can also put trees/heaps in an array Root is at 1 (discuss root at 0 later) left(i) = 2*i right(i) = 2*i + 1

Balanced v. Unbalanced in Arrays Find the array layout of these two trees Root is at 1 left(i) = 2*i right(i) = 2*i + 1 Q: How big of array is required?

Balanced v. Unbalanced in Arrays 0 1 2 3 4 5 6 48 17 89 3 25 63 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 17 3 48 25 89 63

Complete Trees Only "missing" nodes in their bottom row (level set) Nodes in bottom row are as far left as possible Not Complete (Why?) Complete Complete trees don t waste space in arrays: no gaps Hard for general BSTs, easy for binary heaps...

Trees/Heaps in Array: Keep them Complete Storing in arrays: can cost space overhead If the tree is complete or nearly so, little wasted space BSTs in arrays Hard to keep tree complete BST + balancing property makes it hard Rotations may not be constant time anymore Trees not usually laid out in arrays: linked nodes much more common Binary Heaps in arrays Very easy to keep tree complete Heap Property is more loose, easier to maintain No rotations, no worries.. Binary heaps almost always laid out in arrays

PQ Ops with Binary Heaps Use an internal T array[] of queue contents Maintaint min-heap order in array Define Tree-like ops for array[] root() => 1 left(i) => i*2 right(i) => i*2 + 1 parent(i) => i / 2 T findmin() Super easy return array[root()]; insert(t x) Ensure heap is a complete tree Insert at next array[size] Increment size Percolate new element up deletemin() Ensure heap is a complete tree Decrement size Replace root with last data Percolate root down

Demos of Binary Heaps Not allowed on exams, but good for studying Min Heap from David Galles @ Univ SanFran Visualize both heap and array version All ops supported Max Heap from Steven Halim Good visuals No array Slow to load

Operations for Heaps // Binary Heap, 1-indexed public class BinaryHeapPQ<T>{ private T [] array; private int size; // Helpers static int root(){ return 1; static int left(int i){ return i*2; static int right(int i){ return i*2+1; static int parent(int i){ return i / 2; // Insert a data public void insert(t x){ size++; ensurecapacity(size+1); array[size] = x; percolateup(size); // Remove the minimum element public void deletemin(){ array[root()] = array[size]; array[size] = null; size--; percolatedown(root());

Percolate Up/Down Up void percolateup(int xdx){ while(xdx!=root()){ T x = array[xdx]; T p = array[parent(xdx)]; if(docompare(x,p) < 0){ array[xdx] = p; array[parent(xdx)] = x; xdx = parent(xdx); else{ break; Down void percolatedown(int xdx){ while(true){ T x = array[xdx]; int cdx = left(xdx); // Determine which child // if any to swap with if(cdx > size){ break; // No left, bottom if(right(xdx) < size && // Right valid docompare(array[right(xdx)], array[cdx]) cdx = right(xdx); // Right smaller T child = array[cdx]; if(docompare(child,x) < 0){ // child smaller array[cdx] = x; array[xdx] = child; xdx = cdx; else{ break; // swap // reset index

PQ/Binary Heap Code BinaryHeapPQ.java Code distribution today contains working heap percolateup() and percolatedown() do most of the work Uses "root at index 1" convention Text Book Binary Heap Weiss uses a different approach in percolate up/down Move a "hole" around rather than swapping Probably saves 1 comparison per loop iteration Have a look in weiss/util/priorityqueue.java

Complexity of Binary Heap PQ methods? T findmin(); void insert(t x); // x knows its priority void deletemin(); Give the complexity and justify for each

Height Again... Efficiency of Binary Heap PQs findmin() clearly O(1) deletemin() worst case height insert(x) worst case height Height of a Complete Binary Tree wrt number of nodes N? Guesses? Do some googling if you are feeling cowardly...

This is how rumors get started Weiss s Assertion: insert is O(1) On average the percolation [up] terminates early: It has been shown that 2.6 comparisons are required on average to perform the add, so the average add moves an element up 1.6 levels. Weiss 4th ed pg 815 Precise results on the number of comparisons and data movements used by heapsort in the best, worst, and average case are given in (Schaffer and Sedgewick). pg 839 Schaffer and R. Sedgewick, "The Analysis of Heapsort," Journal of Algorithms 14 (1993), 76 100.

And how rumors resolve Binary Heaps DO have O(1) amortized insertion Empirical Evaluation Mathematical Proof Schaffer/Sedgewick (1991) Carlsson (1987) Porter/Simon (1974): "note pg. 15 in which the average case is stated to be upper-bound by lambda, which computes to 1.606691524" Students in Fall 2013 did the above, edited Wikipedia to reflect this fact. You should have been there. It was awesome.

Summary of Binary Heaps Op Worst Case Avg Case findmin() O(1) O(1) insert(x) O(log N) O(1) deletemin() O(log N) O(log N) Notice: No get(x) method or remove(x) methods These would involve searching the whole binary heap/priority queue if they did existed: O(N)