12-1 Priority Queues, Sets, and Bags Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 12 Monday, March 12 Handout #22.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Chapter 7. Binary Search Trees
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Java Review Interface, Casting, Generics, Iterator.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
Reviews for Exam 1 Chapter 1-4 CS 211 Data Structures MHC, 2007.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
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!
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
08 1 Abstract Data Types Problem Sets: PS2 due due Monday, Feburary 26 PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 08 Monday, February 26.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
ArrayList, Multidimensional Arrays
Extensible Arrays: Vectors and StringBuffers Problem Set:Assignment #1 due Tuesday, Feburary 13 Wellesley College CS230 Lecture 05 Monday, February.
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
09-1 Queues and List-Based ADT Implementations Problem Set: PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 09 Monday, February 26 Handout #18.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
13-1 Sets, Bags, and Tables Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 13 Thursday, March 15 Handout #23.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
ICOM 4035 – Data Structures Lecture 4 – Set ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
M180: Data Structures & Algorithms in Java Queues Arab Open University 1.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
9 Set ADTs  Set concepts  Set applications  A set ADT: requirements, contract  Implementations of sets: using member arrays, linked lists, boolean.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Collections Dwight Deugo Nesa Matic
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
An Array-Based Implementation of the ADT List
Linked Data Structures
Lecture 10 Collections Richard Gesick.
Ordered Structures Wellesley College CS230 Lecture 11
The List ADT.
Data Structures and Algorithms for Information Processing
Priority Queues and Heaps
Heaps And Priority Queues
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.
CMSC 341 Lecture 5 Stacks, Queues
structures and their relationships." - Linus Torvalds
CS313D: Advanced Programming Language
structures and their relationships." - Linus Torvalds
EE 422C Sets.
Heaps and Priority Queues
Fundaments of Game Design
Ordered Structures Wellesley College CS230 Lecture 10
Chapter 9 The Priority Queue ADT
Sets CS3240, L. grewe.
structures and their relationships." - Linus Torvalds
CHAPTER 3: Collections—Stacks
Presentation transcript:

12-1 Priority Queues, Sets, and Bags Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 12 Monday, March 12 Handout #22

12-2 Overview of Today’s Lecture 1.More on Priority Queues = ordered queues in which maximal element is dequeued. 2.Sets = conceptually unordered collections of elements without duplicates (but need order on elements to implement efficiently). 3.Bags = conceptually unordered collections of elements with duplicates

12-3 Priority Queues A priority queue is a kind of queue in which deq()/front() return the highest-priority element, where priority is determined by a Comparator. If comparator is null, this indicates use of the natural Comparable ordering. PQueue pq = new PQueue (); // Use null Comparator pq.enq(“beetle”); pq.enq(“cat”); pq.enq(“deer”); pq.enq(“ant”); while (! pq.isEmpty()) System.out.print(pq.deq() + “ “); System.out.println(); “deer”“cat”“beetle”“ant” Dequeue highest element (the greatest by Comparator) deer cat beetle ant

12-4 Specifying a Priority Queue Comparator The following method demonstrates how a pqueue depends on the Comparator: public static void test (PQueue pq) { pq.enq("beetle"); pq.enq("cat"); pq.enq("deer"); pq.enq("ant"); while (!pq.isEmpty()) System.out.print(pq.deq() + " "); System.out.println(); } 1. PQueueTester.test(new PQueueVectorLH ()); 2. PQueueTester.test(new PQueueVectorLH (new LengthComparator())); 3. PQueueTester.test(new PQueueVectorLH ( new ComparatorInverter (new ComparableComparator ()))); 4. PQueueTester.test(new PQueueVectorLH ( new ComparatorInverter (new LengthComparator()))); A particular pqueue implementation that we’ll study later.

12-5 What are Priority Queues Good For? 1. They model situations where certain “to-do” items have a higher priority than others. E.g.: printer queue that prints shorter documents before longer ones; emergency room doctor who performs triage on patients student who works on assignment based on due date/importance 2. They can be use to sort elements: public static void pqsort (Comparator, T[] elts) { } This is a good idea only if an efficient priority queue implementation is used. In particular, heapsort is an efficient sorting algorithm using the heap implementation of a pqueue (later this semester).

12-6 A Priority Queue (PQueue) Interface public interface PQueue extends Queue { public Comparator comparator(); // Returns comparator used by this pqueue to determine priority. // Returns null if the natural Comparable ordering is being used. public void enq(T elt); // Add elt to this pqueue. public T deq(); // Remove and return highest-priority element from this pqueue. public T front(); // Return highest-priority element from this pqueue // without removing it. public Iterator iterator(); // Return an iterator that yields this pqueue's elements from // highest priority to lowest priority. public PQueue copy(); // Return a shallow copy of this pqueue public String toString(); // Return string listing elements of this pqueue from highest priority down. // Inherits the following methods with their usual behavior from Queue : // boolean isEmpty(), int size(); void clear(); // A pqueue implementation should also provide two constructor methods: // 1. A nullary constructor method in which the Comparator is assumed null // 2. A unary constructor method explicitly supplying the Comparator method }

12-7 Suppose we implement a PQueue as a Vector: 1.Should elements be unsorted or sorted? Why? 2.Should elements be sorted low-to-high or high-to-low? Why? Implementing a PQueue as a Vector “bat”“dog”“ant”“cat” 0123 Vector “ant”“bat”“cat”“dog” 0123 Vector “ant”“bat”“cat”“dog” 0123 Vector “dog”“cat”“bat”“ant” 0123 Vector

12-8 PQueueVectorLH: Constructor Methods /** Represent a pqueue as a vector of elements from low to high priority */ public class PQueueVectorLH implements PQueue { // Instance Variables: private Vector elts; // Stores sorted elements private Comparator comp; // Remembers comparator // Constructor Methods: public PQueueVectorLH(Comparator comp) { this.elts = new Vector (); this.comp = comp; } public PQueueVectorLH() { this(null); // null means to use "natural" Comparable ordering } // Instance Methods go here … }

12-9 PQueueVectorLH: Easy Instance Methods // One brand new instance method: public Comparator comparator() { return comp; } // Most instance methods like those in back-to-front queue: public T deq () { if (elts.size() == 0) throw new RuntimeException("Attempt to deq() empty pqueue."); else return elts.remove(elts.size()-1); } public T front () { if (elts.size() == 0) throw new RuntimeException("Attempt to take front() of empty pqueue."); else return elts.get(elts.size()-1); } public boolean isEmpty() { return elts.size() == 0; } public int size() { return elts.size(); } public void clear() { elts = new Vector (); } // copy(), iterator(), and toString() are also like in back-to-front queue.

12-10 PQueueVectorLH: Enqueuing public void enq (T elt) { // Here, use linear search for insertion. Could use binary search instead, but // insertion will generally be linear anyway due to element shifting in vector. int i = elts.size() - 1; while ((i >= 0) && (compare(elt, elts.get(i)) < 0)) { // Loop invariant: all slots in elts at indices > i hold values greater than elt. i--; } // Invariant: i in range [-1..(elts.size() - 1)] is largest i such that all slots // with indices greater than i contain values greater than elt. elts.add(i+1,elt); }

12-11 PQueueVectorLH: Comparing Elements private int compare(T x, T y) { if (comp == null) { // Assume that x is an instance of Comparable. return ((Comparable) x).compareTo(y); // A ClassCastException will be thrown if this assumption is violated. // Note: the Java 1.5 compiler will issue an unchecked warning for the // above line because it cannot prove that the downcast will succeed. } else { return comp.compare(x,y); } queue] javac PQueueVectorLH.java Note: PQueueVectorLH.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. queue] javac -Xlint:unchecked PQueueVectorLH.java PQueueVectorLH.java:29: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable return ((Comparable) x).compareTo(y);

12-12 Using Inheritance to Simplify Implementation QueueVectorBF PQueueVectorLH Implements Queue using vector of elements arranged from back to front Implements PQueue using vector of elements arranged from low to high priority. Can inherit the the following from QueueVectorBF: public T deq(); public T front(); public boolean isEmpty(); public boolean size(); public boolean clear(); public Iterator iterator(); PQueueVectorLH must still implement the following: Constructor methods public Comparator comp(); // new to PQueue public void enq (T elt); // inserts in sorted order public PQueue copy(); // has different return type public String toString(); // has different name extends

12-13 Can Even Inherit toString() public class QueueVectorBF implements Queue { public String toString() { StringBuffer buff = new StringBuffer(); buff.append(name() + "["); … code for listing elements from front to back … buff.append("]"); return buff.toString(); } public String name() {// can be overridden by PQueueVectorLH. return "QueueVectorBF"; } public class PQueueVectorLH extends QueueVectorBF implements PQueue { public String name() {// overrides name() in QueueVectorBF return "PQueueVectorLH"; } … other methods go here … }

12-14 Implementing Priority Queues as a Mutable List We could instead implement a Priority Queue using a mutable list. How should elements be arranged? What is the code for enq(), deq(), front()?

12-15 Priority Queues Implementation Summary Using vectors or lists, all priority queue operations can be implemented efficiently except for enq(): Constructor methods, front(), deq(), size(), isEmpty(), clear() take constant time. copy(), toString(), and iterator() take time linear in number of elements (iterator() can be changed to constant time). enq() takes time linear in number of elements: BAD!!!

12-16 Mathematical Sets In mathematics, a set is an unordered collection of elements w/o duplicates. A set is written by enumerating its elements between braces. E.g., the empty set (with no elements) is written {}. Insertion: inserts an element into a set if it’s not already there: insert(“a”, {}) = {“a”} insert(“b”, {“a”}) = {“a”, “b”} = {“b”, “a”} // order is irrelevant insert(“a”, {“a”, “b”}) = {“a”, “b”} = {“b”, “a”} insert(“c”, {“a”,”b”}) = {“a”, “b”, “c”} = {“a”, “c”, “b”} = {“b”, “a”, “c”} = {“b”, “c”, “a”} = {“c”, “a”, “b”} = {“c”, “b”, “a”} Deletion: removes an element if it’s in the set: delete(“a”, {}) = {} delete(“a”, {“a”, ”b”}) = {“b”} delete(“b”, {“a”, ”b”}) = {“a”} delete(“c”, {“a”, “b”}) = {“a”, “b”} Size (Cardinality): |S| is the number of elements in S. |{}| = 0; |{“a”}| = 1; |{“a”, “b”}| = 2; |{“a”, “b”, “c”}| = 3;

12-17 More Sets Membership: x  S is true if x is in the set S and false otherwise. “a”  {} = false; “a”  {“a”, “b”} = true; “c”  {“a”, “b”} = false; Subset: S1  S2 is true if all elements in S1 are also in S2. {}  {“a”, “b”} is true; {“a”}  {“a”, “b”} is true; {“b”}  {“a”, “b”} is true; {“a”, “b”}  {“a”, “b”} is true; {“a”, “b”}  {“a”} is false; {“a”}  {} is false; Union: S1  S2 = all elements in at least one of S1 and S2. {“a”, “b”, “d”, “e”}  {“b”, “c”, “d”, “f”} = {“a”, “b”, “c”, “d”, “e”, “f”} Intersection: S1  S2 = all elements in at both S1 and S2. {“a”, “b”, “d”, “e”}  {“b”, “c”, “d”, “f”} = {“b”, “d”} Difference: S1 - S2 or S1/S2 = all elements in S1 that are not in S2. {“a”, “b”, “d”, “e”} / {“b”, “c”, “d”, “f”} = {“a”, “e”}

12-18 Mathematical Bags (Multi-Sets) In mathematics, a bag (multi-set) is an unordered collection of elements with duplicates. A bag is written by enumerating its elements (with duplicates) between braces. E.g., the empty bag (with no elements) is written {}. The bag with one “a” is written {“a”, “a”}. The bag with two “a”s is written {“a”, “a”}. Most set notions (insertion, deletion, membership, subset, union, intersection, difference, cardinality) generalize to bags as long as duplicates are accounted for. E.g: insert(“a”, {“a”, “b”}) = {“a”,“a”, “b”} = {“a”, “b”, “a”} = {“b”, “a”, “a”} delete(“a”, {“a”, “a”, “a”, “b”, “c”, “c”}) = {“a”,“a”, “b”, “c”, “c”} {“a”, “b”}  {“a”, “a”, “b”} = true; {“a”, “a”, “b”}  {“a”, “b”} = false; {“a”, “a”, “b”, “d”}  {“a”, “d”, “e”} = {“a”, “a”, “a”, “b”, “d”, “d”, “e”} {“a”, “a”, “a”, “b”, “c”}  {“a”, “a”, “b”, “b”} = {“a”, “a”, “b”} {“a”, “a”, “a”, “b”, “c”} / {“a”, “a”, “b”, “b”} = {“a”, “c”} |{“a”, “a”, “a”, “b”, “c”, “c”}| = 6

12-19 New Bag Operations Multiplicity: we shall write #(x,B) (my nonstandard notation) for the number of occurrences of element x in bag B, a.k.a. the multiplicity of x in B. Suppose B1 = {“a”,”a”, “a”, “b”, “c”, “c”}. Then: #(“a”, B1) = 3; #(“b”, B1) = 1; #(“c”, B1) = 2; #(“d”, B1) = 0; DeleteAll: delete(x,B) deletes one occurrence of x from B. Sometimes we want to delete all occurrences of x from B. For this we use deleteAll(x,B). delete(“a”, {“a”, “a”, “a”, “b”, “c”, “c”}) = {“a”,“a”, “b”, “c”, “c”} deleteAll(“a”, {“a”, “a”, “a”, “b”, “c”, “c”}) = {“b”, “c”, “c”} deleteAll(“d”, {“a”, “a”, “a”, “b”, “c”, “c”}) = {“a”, “a”, “a”, “b”, “c”, “c”} CountDistinct: |B| counts all element occurrences in B, including duplicates. Sometimes we want just the number of distinct elements. For this we use countDistinct(B). |{“a”, “a”, “a”, “b”, “c”, “c”}| = 6 countDistinct({“a”, “a”, “a”, “b”, “c”, “c”}) = 3

12-20 Digression: Ordered Sets and Bags Sets and bags are unordered collections of elements. However, we can also have ordered notions of sets and bags, in which the order of elements matters. The order might be specified by a Comparator or the Comparable compareTo() method, in which case elements would have a well-defined index. For instance, in the ordered bag OB{“a”, “a”, “a”, “b”, “c”, “c”} “a”s are at indices 0, 1, 2; “b” is at index 3, and “c”s are at indices 4 & 5. Since elements have a well-defined index, we could request the element at a given index or delete the element at an index from an ordered set/bag. Inserting elements into or deleting elements from an ordered set/bag can shift the indices of other elements, similar to what happens in a vector. We will not consider implementations of ordered sets or bags this semester.