PRIORITY QUEUES AND HEAPS Lecture 16 CS2110 Fall 2014.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring
Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element.
1 6.3 Binary Heap - Other Heap Operations There is no way to find any particular key without a linear scan through the entire heap. However, if we know.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
CS 261 – Data Structures Priority Queues & Heaps.
1 CS211, Lecture 20 Priority queues and Heaps Readings: Weiss, sec. 6.9, secs When they've got two queues going, there's never any queue!
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)
PRIORITY QUEUES AND HEAPS Lecture 16 CS2110 Spring 2015.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
COMP 103 Priority Queues, Partially Ordered Trees and Heaps.
Heaps, Heapsort, Priority Queues. Sorting So Far Heap: Data structure and associated algorithms, Not garbage collection context.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
PRIORITY QUEUES AND HEAPS Lecture 16 CS2110 Spring 2015.
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 and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
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.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
Lecture 8 : Priority Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Heaps and basic data structures David Kauchak cs161 Summer 2009.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
"Teachers open the door, but you must enter by yourself. "
Priority Queues and Heaps
Priority Queues and Heaps
Heaps And Priority Queues
Hashing Exercises.
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.
Heaps and Priority Queue
Heaps & Priority Queues
Chapter 8 – Binary Search Tree
CSE 373: Data Structures and Algorithms
"Teachers open the door, but you must enter by yourself. "
Data Structures and Analysis (COMP 410)
Priority Queues & Heaps
Heaps and Priority Queues
Binary and Binomial Heaps
HEAPS.
Priority Queues.
Priority Queues CSE 373 Data Structures.
Priority Queues & Heaps
Heaps & Multi-way Search Trees
Presentation transcript:

PRIORITY QUEUES AND HEAPS Lecture 16 CS2110 Fall 2014

Reminder: A4 Collision Detection  Due tonight by midnight 2

Readings and Homework Read Chapter 26 “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? 3 With ZipUltra heaps, you’ve got it made in the shade my friend!

The Bag Interface A Bag: interface Bag { void insert(E obj); E extract(); //extract some element boolean isEmpty(); } Refinements of Bag: Stack, Queue, PriorityQueue 4 Like a Set except that a value can be in it more than once. Example: a bag of coins

Stacks and Queues as Lists 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 These operations are O(1) first last 5

Priority Queue 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 6

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 Examples of Priority Queues 7

java.util.PriorityQueue 8 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() {...}

Priority Queues as Lists 9 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?

Important Special Case 10 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 11 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

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

Smallest element in any subtree is always found at the root of that subtree Note: 19, 20 < 35: Smaller elements can be deeper in the tree! Heaps 13

Examples of Heaps 14 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 15 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 16 d =

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

children of node n are found at 2n + 1 and 2n Store in an ArrayList or Vector 18

Store in an ArrayList or Vector children of node n are found at 2n + 1 and 2n

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

insert()

insert()

insert()

insert()

insert()

insert()

insert()

insert()

insert()

insert()

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

/** An instance of a priority queue */ class PriorityQueue extends java.util.Vector { /** 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 } 32 insert()

class PriorityQueue extends java.util.Vector { /** 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; } 33 insert()

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! 34 extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

extract()

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

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

/** 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--; // inv tree is a heap except: element k may be > than a child. // Also k’s smallest child is element c while (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--; } 51

HeapSort 52 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 pq= new PriorityQueue (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.

Many uses of priority queues & heaps  Mesh compression: quadric error mesh simplification  Event-driven simulation: customers in a line  Collision detection: "next time of contact" for colliding bodies  Data compression: Huffman coding  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  Spam filtering: Bayesian spam filter 53 Surface simplification [Garland and Heckbert 1997]

54

PQ Application: Simulation  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! 55