L17cs2110fa09-6up - 10/27/2009 1 The Bag Interface 2 A Bag:...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
10/27/2009 1 1 PRIORITY QUEUES AND HEAPS Lecture 17 CS2110 Fall 2009 The Bag Interface ± A Bag: interface Bag<E> { void insert(E obj); Ett ( ) // t t l t 2 E extract(); //extract some element boolean isEmpty(); } Examples: Stack, Queue, PriorityQueue Stacks and Queues as Lists •Stack (LIFO) implemented as list insert() , extract() from front of list •Queue (FIFO) implemented as list 3 insert() on back of list, extract() from front of list •All Bag operations are O(1) 55 120 19 16 first last Priority Queue •A Bag in which data items are Comparable lesser elements (as determined by compareTo() ) have higher priority 4 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 5 • 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> boolean add(E e) {. ..} //insert an element (insert) void clear() {. ..} //remove all elements E peek() {. ..} //return min element without removing 6 //(null if empty) E poll() {. ..} //remove min element (extract) //(null if empty) int size() {. ..}
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
10/27/2009 2 Priority Queues as Lists • Maintain as unordered list insert() puts new element at front – O(1) extract() must search the list – O(n) 7 • Maintain as ordered list insert() must search the list – O(n) extract() gets element at front – O(1) • In either case, O(n 2 ) to process n elements Can we do better?
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/08/2010 for the course CS 2110 taught by Professor Francis during the Spring '07 term at Cornell University (Engineering School).

Page1 / 8

L17cs2110fa09-6up - 10/27/2009 1 The Bag Interface 2 A Bag:...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online