PRIORITY QUEUES AND HEAPS. Lecture 19 CS2110 Spring 2014

Similar documents
PRIORITY QUEUES AND HEAPS

PRIORITY QUEUES AND HEAPS. Slides of Ken Birman, Cornell University

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 17: Heaps and Priority Queues

RBT Operations. The basic algorithm for inserting a node into an RBT is:

CSS 343 Data Structures, Algorithms, and Discrete Math II. Balanced Search Trees. Yusuf Pisan

CSE 100: RED-BLACK TREES

Chapter 7: Sorting 7.1. Original

Programming Abstractions

4.4 Shortest Paths in a Graph Revisited

Topic 23 Red Black Trees

CSI33 Data Structures

Balanced Trees. Balanced Trees Tree. 2-3 Tree. 2 Node. Binary search trees are not guaranteed to be balanced given random inserts and deletes

MITOCW 6. AVL Trees, AVL Sort

COS 226 Algorithms and Data Structures Fall Midterm Exam

ARTIFICIAL INTELLIGENCE (CS 370D)

Link State Routing. Brad Karp UCL Computer Science. CS 3035/GZ01 3 rd December 2013

CS : Data Structures

1 Permutations. Example 1. Lecture #2 Sept 26, Chris Piech CS 109 Combinatorics

Binary trees. Application: AVL trees and the golden ratio. The golden ratio. φ 1=1/φ 1. φ =1+

CS188 Spring 2014 Section 3: Games

Huffman Coding - A Greedy Algorithm. Slides based on Kevin Wayne / Pearson-Addison Wesley

5 AVL trees: deletion

Skip Lists S 3 S 2 S 1. 2/6/2016 7:04 AM Skip Lists 1

COS 226 Algorithms and Data Structures Fall Midterm Exam

Binary Search Tree (Part 2 The AVL-tree)

Past questions from the last 6 years of exams for programming 101 with answers.

mywbut.com Two agent games : alpha beta pruning

Permutations. Example 1. Lecture Notes #2 June 28, Will Monroe CS 109 Combinatorics

Self-Adjusting Binary Search Trees. Andrei Pârvu

CS 540-2: Introduction to Artificial Intelligence Homework Assignment #2. Assigned: Monday, February 6 Due: Saturday, February 18

Announcements. Homework 1 solutions posted. Test in 2 weeks (27 th ) -Covers up to and including HW2 (informed search)

Homework Assignment #2

1 Permutations. 1.1 Example 1. Lisa Yan CS 109 Combinatorics. Lecture Notes #2 June 27, 2018

Homework Assignment #1

MITOCW ocw lec11

MITOCW R11. Principles of Algorithm Design

MITOCW watch?v=krzi60lkpek

Link State Routing. Stefano Vissicchio UCL Computer Science CS 3035/GZ01

Section Marks Agents / 8. Search / 10. Games / 13. Logic / 15. Total / 46

Games and Adversarial Search II

CSE 100: BST AVERAGE CASE AND HUFFMAN CODES

UNIVERSITY of PENNSYLVANIA CIS 391/521: Fundamentals of AI Midterm 1, Spring 2010

Outline. EEC-484/584 Computer Networks. Homework #1. Homework #1. Lecture 8. Wenbing Zhao Homework #1 Review

Introduction to. Algorithms. Lecture 10. Prof. Constantinos Daskalakis CLRS

Introduction to. Algorithms. Lecture 10. Prof. Piotr Indyk

CS445: Modeling Complex Systems

Grading Delays. We don t have permission to grade you (yet) We re working with tstaff on a solution We ll get grades back to you as soon as we can

Diffracting Trees and Layout

Module 3 Greedy Strategy

Search then involves moving from state-to-state in the problem space to find a goal (or to terminate without finding a goal).

CSE373: Data Structure & Algorithms Lecture 23: More Sorting and Other Classes of Algorithms. Nicki Dell Spring 2014

Game Theory and Randomized Algorithms

Lectures: Feb 27 + Mar 1 + Mar 3, 2017

The Theory Behind the z/architecture Sort Assist Instructions

Compiler Optimisation

CS188 Spring 2010 Section 3: Game Trees

A Note on Downup Permutations and Increasing Trees DAVID CALLAN. Department of Statistics. Medical Science Center University Ave

ECE 242 Data Structures and Algorithms. Simple Sorting II. Lecture 5. Prof.

From ProbLog to ProLogic

DATA STRUCTURE TREES UNIT II

5. Process and thread scheduling

Computer Graphics (CS/ECE 545) Lecture 7: Morphology (Part 2) & Regions in Binary Images (Part 1)

Implementing an intelligent version of the classical sliding-puzzle game. for unix terminals using Golang's concurrency primitives

Adversary Search. Ref: Chapter 5

Module 3 Greedy Strategy

(Lec19) Geometric Data Structures for Layouts

AIMA 3.5. Smarter Search. David Cline

AC : MOTIVATING STUDENTS TO LEARN PROGRAMMING USING GAME ASSIGNMENTS

AI Approaches to Ultimate Tic-Tac-Toe

Generalized Game Trees

CSc 110, Spring Lecture 40: Sorting Adapted from slides by Marty Stepp and Stuart Reges

Informatica Universiteit van Amsterdam. Performance optimization of Rush Hour board generation. Jelle van Dijk. June 8, Bachelor Informatica

CS 441/541 Artificial Intelligence Fall, Homework 6: Genetic Algorithms. Due Monday Nov. 24.

COCI 2008/2009 Contest #3, 13 th December 2008 TASK PET KEMIJA CROSS MATRICA BST NAJKRACI

CS188 Spring 2010 Section 3: Game Trees

Lab 6 This lab can be done with one partner or it may be done alone. It is due in two weeks (Tuesday, May 13)

CS 787: Advanced Algorithms Homework 1

Game Engineering CS F-24 Board / Strategy Games

Merge Sort. Note that the recursion bottoms out when the subarray has just one element, so that it is trivially sorted.

and 6.855J. Network Simplex Animations

Reverse Auction Addon

Machine Translation - Decoding

Design of Parallel Algorithms. Communication Algorithms

CS 771 Artificial Intelligence. Adversarial Search

COMP 2804 solutions Assignment 4

On Range of Skill. Thomas Dueholm Hansen and Peter Bro Miltersen and Troels Bjerre Sørensen Department of Computer Science University of Aarhus

Data Gathering. Chapter 4. Ad Hoc and Sensor Networks Roger Wattenhofer 4/1

COMP Online Algorithms. Paging and k-server Problem. Shahin Kamali. Lecture 11 - Oct. 11, 2018 University of Manitoba

Conversion Masters in IT (MIT) AI as Representation and Search. (Representation and Search Strategies) Lecture 002. Sandro Spina

Single-Server Queue. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

Event-Driven Scheduling. (closely following Jane Liu s Book)

Fall 2015 COMP Operating Systems. Lab #7

Single-Server Queue. Hui Chen, Ph.D. Computer Science Dept. of Math & Computer Science Virginia State University Petersburg, VA 23806

Contents. Basic Concepts. Histogram of CPU-burst Times. Diagram of Process State CHAPTER 5 CPU SCHEDULING. Alternating Sequence of CPU And I/O Bursts

Checkpoint Questions Due Monday, October 7 at 2:15 PM Remaining Questions Due Friday, October 11 at 2:15 PM

16.410/413 Principles of Autonomy and Decision Making

Topic 1: defining games and strategies. SF2972: Game theory. Not allowed: Extensive form game: formal definition

DVA325 Formal Languages, Automata and Models of Computation (FABER)

Adversarial Search and Game- Playing C H A P T E R 6 C M P T : S P R I N G H A S S A N K H O S R A V I

Real Time Operating Systems Lecture 29.1

Transcription:

1 PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring 2014

Readings and Homework 2 Read Chapter 2 to learn about heaps 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!

The Bag Interface 3 A Bag: interface Bag<E> { void insert(e obj); E extract(); //extract some element } boolean isempty(); 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

Stacks and Queues as Lists 4 Stack (LIFO) implemented as list insert(), extract() from front of list Queue (FIFO) implemented as list insert() on back of list, extract() from front of list All Bag operations are O(1) first 55 120 19 1 last

Priority Queue 5 A Bag in which data items are Comparable lesser elements (as determined by compareto()) have higher priority extract() returns the element with the highest priority = least in the compareto() ordering break ties arbitrarily

Priority Queue Examples Scheduling jobs to run on a computer default priority = arrival time priority can be changed by operator Scheduling events to be processed by an event handler priority = time of occurrence Airline check-in first class, business class, coach FIFO within each class

java.util.priorityqueue<e> 7 boolean add(e e) {...} //insert an element (insert) void clear() {...} //remove all elements E peek() {...} //return min element without removing //(null if empty) E poll() {...} //remove min element (extract) //(null if empty) int size() {...}

8 Priority Queues as Lists Maintain as unordered list insert() put new element at front O(1) extract() must search the list O(n) Maintain as ordered list insert() must search the list O(n) extract() get element at front O(1) In either case, O(n 2 ) to process n elements Can we do better?

9 Important Special Case Fixed number of priority levels 0,...,p 1 FIFO within each level Example: airline check-in insert() insert in appropriate queue O(1) extract() must find a nonempty queue O(p)

Heaps 10 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: insert(): O(log n) extract(): 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

11 Heaps Binary tree with data at each node Satisfies the Heap Order Invariant: The least (highest priority) element of any subtree is found at the root of that subtree Size of the heap is fixed at n. (But can usually double n if heap fills up)

12 Heaps Smallest element in any subtree is always found at the root 4 of that subtree 14 21 8 19 35 22 38 55 10 20 Note: 19, 20 < 35: Smaller elements can be deeper in the tree!

13 Examples of Heaps Ages of people in family tree parent is always older than children, but you can have an uncle who is younger than you Salaries of employees of a company bosses generally make more than subordinates, but a VP in one subdivision may make less than a Project Supervisor in a different subdivision

Balanced Heaps 14 These add two restrictions: 1. Any node of depth < d 1 has exactly 2 children, where d is the height of the tree implies that any two maximal paths (path from a root to a leaf) are of length d or d 1, and the tree has at least 2 d nodes All maximal paths of length d are to the left of those of length d 1

Example of a Balanced Heap 15 4 14 21 8 19 35 22 38 55 10 20 d = 3

Store in an ArrayList or Vector 1 Elements of the heap are stored in the array in order, going across each level from left to right, top to bottom The children of the node at array index n are at indices 2n + 1 and 2n + 2 The parent of node n is node (n 1)/2

Store in an ArrayList or Vector 17 4 0 1 2 14 3 4 5 21 8 19 35 7 8 9 10 11 22 38 55 10 20 children of node n are found at 2n + 1 and 2n + 2

Store in an ArrayList or Vector 18 4 0 1 2 14 3 4 5 21 8 19 35 7 8 9 10 11 22 38 55 10 20 0 1 2 3 4 5 7 8 9 10 11 4 14 21 8 19 35 22 38 55 10 20 children of node n are found at 2n + 1 and 2n + 2

insert() 19 Put the new element at the end of the array If this violates heap order because it is smaller than its parent, swap it with its parent Continue swapping it up until it finds its rightful place The heap invariant is maintained!

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

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

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

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

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

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

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

insert() 27 4 2 21 8 14 5 22 38 55 10 20 19 35

insert() 28 2 4 21 8 14 5 22 38 55 10 20 19 35

insert() 29 2 4 21 8 14 5 22 38 55 10 20 19 35

insert() 30 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

insert() 31 /** An instance of a priority queue */ class PriorityQueue<E> extends java.util.vector<e> { /** Insert e into the priority queue */ public void insert(e e) { super.add(e); //add to end of array bubbleup(size() - 1); // given on next slide }

insert() 32 class PriorityQueue<E> extends java.util.vector<e> { /** Bubble element k up the tree */ private void bubbleup (int k) { int p= (k-1)/2; // p is the parent of k // inv: Every element satisfies the heap property except // element k might be smaller than its parent while (k > 0 && get(k).compareto(get(p)) < 0) { swap elements k and p; k= p; p= (k-1)/2; } }

extract() 33 Remove the least element it is at the root This leaves a hole at the root fill it in with the last element of the array If this violates heap order because the root element is too big, swap it down with the smaller of its children Continue swapping it down until it finds its rightful place The heap invariant is maintained!

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

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

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

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

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

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

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

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

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

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

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

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

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

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

extract() 48 Time is O(log n), since the tree is balanced

49 /** Remove and return the smallest element return null if list is empty) */ public E extract() { } extract() if (size() == 0) return null; E temp= get(0); // smallest value is at root set(0, get(size() 1)); // move last element to the root setsize(size() - 1); // reduce size by 1 bubbledown(0); return temp;

50 /** Bubble the root down to its heap position. Pre: tree is a heap except: root may be >than a child */ private void bubbledown() { int k= 0; // Set c to smaller of k s children int c= 2*k + 2; // k s right child if (c > size()-1 get(c-1).compareto(get(c)) < 0) c= c-1; // inv tree is a heap except: element k may be > than a child. // Also. k s smallest child is element c while (c < size() && get(k).compareto(get(c) > 0) { Swap elements at k and c; k= c; c= 2*k + 2; // k s right child if (c > size()-1 get(c-1).compareto(get(c)) < 0) c= c-1; } }

51 HeapSort Given a Comparable[] array of length n, Put all n elements into a heap O(n log n) Repeatedly get the min O(n log n) public static void heapsort(comparable[] b) { PriorityQueue<Comparable> pq= new PriorityQueue<Comparable>(b); for (int i = 0; i < b.length; i++) { b[i] = pq.extract(); } } One can do the two stages in the array itself, in place, so algorithm takes O(1) space.

PQ Application: Simulation 52 Example: Probabilistic model of bank-customer arrival times and transaction times, how many tellers are needed? Assume we have a way to generate random inter-arrival times Assume we have a way to generate transaction times Can simulate the bank to get some idea of how long customers must wait Time-Driven Simulation Check at each tick to see if any event occurs Event-Driven Simulation Advance clock to next event, skipping intervening ticks This uses a PQ!