CSE 2123: Collections: Priority Queues. Jeremy Morris

Similar documents
Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Binary Heap Algorithms

Binary Heaps. CSE 373 Data Structures

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Big O and Limits Abstract Data Types Data Structure Grand Tour.

dictionary find definition word definition book index find relevant pages term list of page numbers

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

The ADT Binary Search Tree

6 March Array Implementation of Binary Trees

Data Structures in the Java API

cs2010: algorithms and data structures

Algorithms and Data Structures Written Exam Proposed SOLUTION

Sample Questions Csci 1112 A. Bellaachia

Analysis of a Search Algorithm

LINKED DATA STRUCTURES

Practical Session 4 Java Collections

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Chapter 7: Sequential Data Structures

Cpt S 223. School of EECS, WSU

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

From Last Time: Remove (Delete) Operation

CompSci-61B, Data Structures Final Exam

Ordered Lists and Binary Trees

Data Structures Fibonacci Heaps, Amortized Analysis

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Data Structure [Question Bank]

Analysis of Binary Search algorithm and Selection Sort algorithm

Analysis of Algorithms I: Binary Search Trees

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

Stacks. Data Structures and Data Types. Collections

Full and Complete Binary Trees

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Binary Search Trees (BST)

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

7.1 Our Current Model

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

PES Institute of Technology-BSC QUESTION BANK

Quick Sort. Implementation

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Project 4 DB A Simple database program

Introduction to Data Structures

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Data Structures and Algorithms

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Algorithms and Data Structures

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)

Binary Trees and Huffman Encoding Binary Search Trees

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Sequential Data Structures

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Searching Algorithms

1/1 7/4 2/2 12/7 10/30 12/25

Chapter 8: Bags and Sets

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 14 The Binary Search Tree

Data Structures and Data Manipulation

Algorithms and Data Structures

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

D06 PROGRAMMING with JAVA

Load Balancing. Load Balancing 1 / 24

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

AP Computer Science Java Mr. Clausen Program 9A, 9B

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Converting a Number from Decimal to Binary

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

CmpSci 187: Programming with Data Structures Spring 2015

Linked Lists Linked Lists, Queues, and Stacks

Why Use Binary Trees?

Lecture Notes on Binary Search Trees

Data Structures. Algorithm Performance and Big O Analysis

1.204 Lecture 10. Greedy algorithms: Job scheduling. Greedy method

Contents. 9-1 Copyright (c) N. Afshartous

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Chapter 3: Restricted Structures Page 1

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Transcription:

CSE 2123: Collections: Priority Queues Jeremy Morris 1

Collections Priority Queue Recall: A queue is a specific type of collection Keeps elements in a particular order We ve seen two examples FIFO queues Stacks (LIFO queues) What if we want to keep things in a particular order that isn t based on when they entered the queue? Keep elements in sorted order using a priority 2

Collections Priority Queue A priority queue uses queue operations like a FIFO queue or a stack But when remove is called, the element with the most urgent priority is returned Instead of the element put first into the queue or last into the queue For the Java implementation of a priority queue, lower values have a more urgent priority Something with a priority of 1 will be removed before something with a priority of 10 This of this as a ranked list of items the #1 football team has a higher priority than the #10 team 3

Collections Priority Queue Priority queue processing relies on a few standard methods (that should be familiar): Add an object to the queue: void add(e obj) Retrieve (and remove) the item with the lowest score from the queue E remove() Examine the next item in the queue without removing it: E peek() Test to see if the queue is empty: boolean isempty() 4

Collections Priority Queue Java uses the PriorityQueue class to implement a priority queue A priority queue of Integers: PriorityQueue<Integer> intqueue = new PriorityQueue<Integer>(); A priority queue of Strings: PriorityQueue<String> strqueue = new PriorityQueue<String>(); 5

Collections Priority Queues What do we use for rankings (priorities)? Numeric types (Integer, Double) are in the obvious order (ascending by value) For boolean values, false comes before true Characters are ordered by their numeric (Unicode) value Strings are ordered lexicographically Similar to how words are ordered in the dictionary See pages 92-93 in the text or the Java API documentation for the compareto method of String for details 6

Collections Priority Queues What do we use for rankings (priorities) for other types? Java s priority queue implementation requires that we implement the Comparable interface for anything we want to put into it We must write a compareto method for any classes we want to use with a PriorityQueue As with TreeSets and TreeHash 7

Example Priority Queue public static void main(string[] args) { // TODO Auto-generated method stub PriorityQueue<Integer> myqueue = new PriorityQueue<Integer>(); myqueue.add(10); myqueue.add(5); myqueue.add(22); System.out.println("QUEUE: "+myqueue); } while (!myqueue.isempty()) { int head = myqueue.remove(); System.out.print("HEAD: "+head+" "); System.out.println("QUEUE: "+myqueue); } 8

Collections Priority Queue (Heaps) Priority queues are often implemented using a data structure known as a heap This is how the PriorityQueue class is implemented in Java A heap is another form of binary tree It is NOT a binary search tree Instead we want to keep our element with the most urgent priority (smallest value) as the root node of the heap 9

Heaps must satisfy a heap ordering property Heaps can either be min heaps or max heaps, determined by their ordering property For Java s PriorityQueue, the min heap property is used (and that will be the one we discuss here) The min heap property states that the value of each node is always greater than or equal to the value of its parent That ensures that the node with the minimum value will be at the root 10

Suppose we have the elements {1, 3, 7, 10, 19, 22} stored in a heap The heap constructed might look like the tree to the right 3 1 7 The heap creates a complete binary tree filling in nodes across each level 10 19 22 11

Suppose we have the elements {1, 3, 7, 10, 19, 22} stored in a heap The heap constructed might look like the tree to the right 3 1 7 The heap creates a complete binary tree filling in nodes across each level 10 19 22 Now suppose we remove our first element (our most urgent value in the min node) 12

Now suppose we remove our first element (our most urgent value in the min node) We need a new root node 1 3 22 7 How can we preserve our min heap property? When the root node is removed, we automatically swap in the bottom node of the priority queue 10 19 13

When the root node is removed, we automatically swap in the bottom node of the priority queue 1 3 22 7 The min heap property is violated, so our remove is not finished yet Next we need fix our tree so that the heap property is maintained 10 19 The root is swapped with its child that has the smallest value 14

The root is swapped with its child that has the smallest value 1 3 We re still not done our heap property is still violated 22 7 So our node is again swapped with its child that has the smallest value 10 19 15

We re still not done our heap property is still violated 1 3 So our node is again swapped with its child that has the smallest value 10 7 At this point we re finished We have our value taken off the priority queue 22 19 The min heap property is no longer violated The root node is our minimum value and is in position to be removed next 16

What about if we need to add something to our heap? 3 This operates like remove in reverse Instead of moving a bad root node down the heap, we ll move a good node up the heap 10 7 We stop when we reach the spot in the heap where our node should be 22 19 Let s add the value of 2 to our heap 17

Let s add the value of 2 to our heap 3 The 2 is added to the bottom of the heap We re in violation of our min heap property 10 7 So we swap the child with its parent 22 19 2 18

We re in violation of our min heap property 3 So we swap the child with its parent We re still in violation of our min heap property, so we keep going 10 2 We swap our inserted node with its new parent 22 19 7 19

We swap our inserted node with its new parent 2 And now we re done Our min heap property is satisfied 10 3 No more swaps are needed 22 19 7 20

Notice that our min heap property is maintained just by applying a few simple rules Always insert at the bottom of the heap When we insert, check to see if the parent of our new node is larger If it is, swap them and repeat until the parent is smaller or our new node is the root node Remove nodes from the top of the heap When we remove, move the bottom node up to the root Check to see if our new root node is larger than its children If it is, swap it with the smallest of its children and repeat until all children are larger or we hit the bottom of the heap 21

Using these rules we can build a heap Suppose we have the elements {7, 10, 3, 22, 1, 19} to store in a heap We ll add them in that order First we add the 7 Nothing in the heap yet It has no parents The heap property is satisfied 7 22

Using these rules we can build a heap Suppose we have the elements {7, 10, 3, 22, 1, 19} to store in a heap We ll add them in that order First we add the 7 Next the 10 Add it to the bottom Compare to its parent The heap property is satisfied 10 7 23

{7, 10, 3, 22, 1, 19} Next the 3 Add it to the bottom Compare to its parent The heap property is NOT satisfied Swap it with its parent 7 10 3 24

{7, 10, 3, 22, 1, 19} Next the 3 Add it to the bottom Compare to its parent The heap property is NOT satisfied Swap it with its parent Now the heap property is satisfied 3 10 7 25

{7, 10, 3, 22, 1, 19} Next the 22 Add it to the bottom Compare to its parent The heap property is satisfied 22 3 10 7 26

{7, 10, 3, 22, 1, 19} Next the 1 Add it to the bottom Compare to its parent The heap property is NOT satisfied Swap it with its parent 22 1 3 10 7 27

{7, 10, 3, 22, 1, 19} Next the 1 Add it to the bottom Compare to its parent The heap property is NOT satisfied Swap it with its parent The heap property is STILL NOT satisfied Swap it with its new parent 22 10 3 1 7 28

{7, 10, 3, 22, 1, 19} Next the 1 Add it to the bottom Compare to its parent The heap property is NOT satisfied Swap it with its parent The heap property is STILL NOT satisfied Swap it with its new parent Now the heap property is satisfied 22 10 1 3 7 29

{7, 10, 3, 22, 1, 19} Next the 19 Add it to the bottom Compare to its parent The heap property is satisfied 1 3 7 22 10 19 30

Your Turn - Heaps Provide the heap that would result if the following integers were added to the tree in the given order: [ 8, 3, 23, 15, 1, 5, 42, 64, 36 ] Provide heap that would result if the following characters were added in the given order: [ r, q, z, a, c, l, x, w, b ] 31

Collections Priority Queue So when is it good to use a PriorityQueue in Java? With the heap implementation, finding the smallest value is constant time It s always at the top of the heap Removing the minimum element or adding a new element is at worst log n time We may need to make up to log n swaps to maintain our heap property Finding an arbitrary element in the heap is at worst linear time Worst case we have to examine every node! 32

Collections Priority Queue So when is it good to use a PriorityQueue in Java? When we restrict ourselves to queue operations Working only in priority order Don t need to access elements in the middle of the pack 33

Example 2 Priority Queue public static void main(string[] args) { // TODO Auto-generated method stub PriorityQueue<String> myqueue = new PriorityQueue<String>(); myqueue.add( Marley, Bob ); myqueue.add( Cool, Joe ); myqueue.add( Brown, Charles ); System.out.println("QUEUE: "+myqueue); } while (!myqueue.isempty()) { String head = myqueue.remove(); System.out.print("HEAD: "+head+" "); System.out.println("QUEUE: "+myqueue); } 34