Ordered Structures Wellesley College CS230 Lecture 11

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

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.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Written by: Dr. JJ Shepherd
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Queues, Deques, and Priority Queues Chapter Chapter Contents Specifications for the ADT Queue Using a Queue to Simulate a Waiting Line The Classes.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
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.
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Generic abstraction  Genericity  Generic classes  Generic procedures Programming Languages 3 © 2012 David A Watt, University of Glasgow.
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.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
12-1 Priority Queues, Sets, and Bags Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 12 Monday, March 12 Handout #22.
13-1 Sets, Bags, and Tables Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 13 Thursday, March 15 Handout #23.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Written by: Dr. JJ Shepherd
Generics Starring: Rite-Aid Aspirin Co-Starring: CVS Paper Plates.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
Sequential (Linear) Binary Selection** Insertion** Merge.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Linked Data Structures
Prof. U V THETE Dept. of Computer Science YMA
The List ADT.
Lecture 5 of Computer Science II
Priority Queues and Heaps
Week 4 - Friday CS221.
Lecture 5: Some more Java!
Heaps And Priority Queues
Recitation 11 Lambdas added to Java 8.
Stacks.
Implementing ArrayList Part 1
public class StrangeObject { String name; StrangeObject other; }
Heaps & Priority Queues
Iteration Abstraction
Queue, Deque, and Priority Queue Implementations
Queue, Deque, and Priority Queue Implementations
A Data Structure Bestiary
Sorts.
CSE 1030: Implementing Non-Static Features
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Recitation 5 CS0445 Data Structures
CS 2430 Object Oriented Programming and Data Structures I
Initializing Objects.
int [] scores = new int [10];
Queues CSC212.
Lexical Ordering and Sorting
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
CS 2430 Object Oriented Programming and Data Structures I
1 Lecture 10 CS2013.
CSE 373 Advanced heap implementation; ordering/Comparator
slides created by Alyssa Harding
ITI Introduction to Computing II Lab-12
Building Java Programs
Podcast Ch22a Title: Array-based Binary Trees
Workshop for CS-AP Teachers
Ordered Structures Wellesley College CS230 Lecture 10
Arrays Wellesley College CS230 Lecture 02 Thursday, February 1
Chapter 9 The Priority Queue ADT
8 List ADTs List concepts. List applications.
CSE 143 Lecture 21 Advanced List Implementation
Review of Classes and Arrays
Sorting.
Linked Lists Chapter 5 (continued)
The Queue ADT Definition A queue is a restricted list, where all additions occur at one end, the rear, and all removals occur at the other end, the front.
More Binary Trees Wellesley College CS230 Lecture 18 Monday, April 9
Presentation transcript:

Ordered Structures Wellesley College CS230 Lecture 11 Thursday, March 8 Handout #21 Revised Friday, March 9 Exam 1 due Friday, March 16

Overview of Today’s Lecture Insertion sort on integer arrays. Using Comparable<T> and Comparator<T> for more general orderings. Some other approaches to sorting Priority Queues = ordered queues in which maximal element is dequeued.

Insertion Sort on Integer Arrays 7 1 6 2 3 3 9 4 public static void insertionSort (int[] a) { for (int i = 1; i < a.length; i++) { insert(a, i); //Assume a[0..(i-1)] is sorted // Insert a[i] so that a[0..i] is sorted } 6 1 7 2 3 3 9 4 3 1 6 2 7 3 9 4 3 1 6 2 7 3 9 4 3 1 4 2 6 3 7 4 9

Inserting One Element 3 6 7 9 val 4 //Assume a[0..(i-1)] is sorted 3 1 6 2 7 3 9 4 val 4 //Assume a[0..(i-1)] is sorted // Insert a[i] so that a[0..i] is sorted public static void insert (int[] a, int i) { } j 3 1 6 2 7 3 9 4 9 val 4 j 3 1 6 2 7 3 7 4 9 val 4 j 3 1 6 2 6 3 7 4 9 val 4 j 3 1 4 2 6 3 7 4 9 val 4

Insertion Sort in One Method public static void insertionSort (int [] a) { // Outer loop to process elements left-to-right for (int i = 1; i < a.length; i++) { int val = a[i]; int j = i; // Inner loop to insert an element to left in sorted order while ((j > 0) && (val < (a[j-1]))) { // Order of tests is crucial! a[j] = a[j-1]; // Shift value right = shift hole left. j = j-1; } // Now, either (j = 0) or ((j > 1) && (val >= a[j-1])) a[j] = val;

Generalizing to an Array of Comparables The Comparable<T> interface: public interface Comparable<T> { // Compare me to the otherGuy public int compareTo (T otherGuy); } A version of insertionSort() that works for any array of comparable elements: public static <T extends Comparable<T>> void insertionSort (T[] a) { for (int i = 1; i < a.length; i++) { T val = a[i]; int j = i; while ((j > 0) && (val.compareTo(a[j-1]) < 0)) { // Order of tests is crucial! a[j] = a[j-1]; // Shift value right = shift hole left. j = j-1; // Now, either (j = 0) or ((j > 1) && (val.compareTo(a[j-1]) >= 0)) a[j] = val;

Testing insertionSort() on Comparables [fturbak@puma utils] java ArrayOps insertionSort "{I,do,not,like,green,eggs,and,ham}" Before: a = {"I","do","not","like","green","eggs","and","ham"}; insertionSort(a); After: a = {"I","and","do","eggs","green","ham","like","not"} [fturbak@puma utils] java ArrayOps insertionSort "{i,do,not,like,green,eggs,and,ham}" Before: a = {"i","do","not","like","green","eggs","and","ham"}; After: a = {"and","do","eggs","green","ham","i","like","not"}

Using an Explicit Comparator The Comparator<T> interface: public interface Comparator<T> { public int compare (T x, T y); // Compare x to y } A version of insertionSort() that takes an explicit comparator: public static <T> void insertionSort (Comparator<T> comp, T[] a) { for (int i = 1; i < a.length; i++) { T val = a[i]; int j = i; while ((j > 0) && (comp.compare(val, a[j-1]) < 0)) { // Order of tests is crucial! a[j] = a[j-1]; // Shift value right = shift hole left. j = j-1; // At this point, either (j = 0) or ((j > 1) && (comp.compare(val, a[j-1]) >= 0)) a[j] = val;

Another String Comparator Here’s a sample nonstandard String comparator. Shorter strings are considered "less" than longer strings; strings of the same length are compared alphabetically. class LengthComparator implements Comparator<String> { public LengthComparator() {} // Can omit this constructor (Java will supply it). public int compare (String s1, String s2) { if (s1.length() < s2.length()) return -1; else if (s1.length() > s2.length()) return 1; else return s1.compareTo(s2); } Let’s try it out: [fturbak@puma utils] java ArrayOps insertionSortLengthComparator "{I,do,not,like,green,eggs,and,ham}" Before: a = {"I","do","not","like","green","eggs","and","ham"}; insertionSort(new LengthComparator(), a); After: a = {"I","do","and","ham","not","eggs","like","green"}

Some Other Comparators Here are some other Comparator classes: public class ComparableComparator<T extends Comparable<T>> implements Comparator<T> { // Constructs a comparator that compares Comparables public ComparableComparator () {} // Can omit this constructor, since Java will supply it. public int compare (T x, T y) { return (x.compareTo(y)); } } public class ComparatorInverter<T> implements Comparator<T> { private Comparator<T> comparator; // Instance variable that remembers comparator to invert // Constructs a comparator that inverts the sense of comp public ComparatorInverter (Comparator<T> comp) { comparator = comp; } public int compare (T x, T y) { return comparator.compare(y,x); } // Invert comparator’s comparison. Let’s see them in action: [fturbak@puma utils] java ArrayOps insertionSortInverted "{I,do,not,like,green,eggs,and,ham}" Before: a = {"I","do","not","like","green","eggs","and","ham"}; insertionSort(new ComparatorInverter<String>(new ComparableComparator<String>()),a); After: a = {"not","like","ham","green","eggs","do","and","I"}

A Priority Queue (PQueue) Interface public interface PQueue<T> extends Queue<T> { public Comparator<T> 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<T> iterator(); // Return an iterator that yields this pqueue's elements from // highest priority to lowest priority. public PQueue<T> 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<T>: // 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 }