Ordered Containers Cmput 115 - Lecture 21 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Linked Lists Linear collections.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2007 Last lecture :( Instructor: Michael Eckmann.
Binary Search Trees Cmput Lecture 23 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
Sorting - Selection Sort Cmput Lecture 10 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is.
Doubly-Linked Lists Cmput Lecture 16 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
Container Traversal Cmput Lecture 20 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Self-Reference - Induction Cmput Lecture 7 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
15-Jun-15 Lists in Java Part of the Collections Framework.
Stacks Cmput Lecture 18 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from.
Circularly-Linked Lists Cmput Lecture 17 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
Sorting - Merge Sort Cmput Lecture 12 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
Self-Reference - Recursion Cmput Lecture 6 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
Object (Data and Algorithm) Analysis Cmput Lecture 5 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Sorting - Insertion Sort Cmput Lecture 11 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is.
Quick Sort Cmput Lecture 13 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
Code Clarity - Comments, Preconditions and Postconditions Cmput Lecture 2 Department of Computing Science University of Alberta ©Duane Szafron 1999.
Cmput Lecture 15 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from the book:
Queues Cmput Lecture 19 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from.
The List Interface Cmput Lecture 14 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
Dictionaries and Hash Tables Cmput Lecture 24 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture.
12-Jul-15 Lists in Java Part of the Collections Framework.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
SAK 3117 Data Structures Chapter 6: LINKED LISTS.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Information and Computer Sciences University of Hawaii, Manoa
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
CPSC 102: Computer Science II Dr. Roy P. Pargas 408 Edwards Hall Office Hours 10:00-11:00 am MWF 2:00-3:00 pm TTh.
Ordered Containers CMPUT Lecture 19 Department of Computing Science University of Alberta ©Duane Szafron 2003 Some code in this lecture is based.
Data structures Abstract data types Java classes for Data structures and ADTs.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Sets and Maps Computer Science 4 Mr. Gerb Reference: Objective: Understand the two basic applications of searching.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
Collections Dwight Deugo Nesa Matic
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
1 CS162: Introduction to Computer Science II Abstract Data Types.
CSCI 62 Data Structures Dr. Joshua Stough September 23, 2008.
The List ADT.
Chapter 5 Ordered List.
Efficiency of in Binary Trees
COP 3503 FALL 2012 Shayan Javed Lecture 8
Chapter 5 Ordered List.
Programming in Java Lecture 11: ArrayList
Collections Framework
Recursive Objects Singly Linked Lists.
Hashing in java.util
Web Design & Development Lecture 6
Presentation transcript:

Ordered Containers Cmput Lecture 21 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 2/25/00

©Duane Szafron About This Lecture In this lecture we will learn about Ordered containers. An ordered container is a container where the order of the elements depends not on the order they are added, but rather on comparisons of the elements that are added.

©Duane Szafron Outline Ordered Containers OrderedStructure Interface OrderedStructure Example OrderedVector class OrderedList class

©Duane Szafron Ordered Containers An ordered container is a container whose elements are ordered by comparing them with each other. This requires a binary operation to be defined that applies to any pair of elements that can be added to the container. In Java, we use the compareTo(Object) method from the Comparable Interface. As each element is added to the container it immediately goes to the proper location in the container based on comparing it with all other elements that are in the container.

©Duane Szafron OrderedStructure Hierarchy The structure package adds the OrderedStructure interface below the Collection interface. Store Collection ListOrderedStructure

©Duane Szafron Structure Interface - Store public interface Store { public int size(); //post: returns the number of elements contained in // the store. public boolean isEmpty(); // post: returns the true iff store is empty. public void clear(); // post: clears the store so that it contains no // elements. } code based on Bailey pg. 18

©Duane Szafron code based on Bailey pg. 19 Structure Interface - Collection public interface Collection extends Store { public boolean contains(Object anObject); // pre: anObject is non-null // post: returns true iff the collection contains the object public void add(Object anObject); // pre: anObject is non-null // post: the object is added to the collection. // Replacement policy is not specified public Object remove(Object anObject); // pre: anObject is non-null // post: removes object “equal” to anObject and returns it, // otherwise returns nil public Iterator elements(); // post: return an iterator for traversing the collection }

©Duane Szafron Structure Interface - OrderedStructure public interface OrderedStructure extends Collection {} code based on Bailey pg. 173 The unusual thing about the OrderedStructure interface is that it does not add any new methods to those provided by Collection. However, any class that implements this interface must ensure that when elements are added, they go to the correct location. In essence, it changes the post condition of the add method in Collection: // post: the object is added to the collection. The // replacement policy is not specified

©Duane Szafron OrderedStructure Example public static void main (String[ ] args) { OrderedStructure container; RandomInt generator; int index; Iterator iterator; container = new OrderedVector(); generator = new RandomInt(1); for (index = 0; index < 100; index++) { container.add(new Integer(generator.next(100)))}; iterator = container.elements(); while(iterator.hasMoreElements()) System.out.print(iterator.nextElement() + ‘ ‘); } code based on Bailey pg

©Duane Szafron OrderedVector - State and Constructor class OrderedVector implements OrderedStructure { protected Vector data; public OrderedVector(){ // post: intitalizes the OrderedVector to have 0 elements this.data = new Vector(); } code based on Bailey pg. 173

©Duane Szafron OrderedVector - Store Interface /* Interface Store Methods */ public int size() { //post: returns the number of elements contained in the store. return this.data.size(); } public boolean isEmpty() { // post: returns the true iff store is empty. return this.size() == 0; } public void clear(); // post: clears the store so that it contains no elements. this.data.clear(); } code based on Bailey pg. 178

©Duane Szafron OrderedVector - contains(Object) /* Interface Collection Methods */ public boolean contains(Object anObject) { // pre: anObject is non-null // post: returns true iff the collection contains the object int index; index = this.indexOf ((Comparable) anObject); return (index < this.size()) && (this.data.elementAt(index).equals(anObject)); } code based on Bailey pg. 176

©Duane Szafron OrderedVector - add(Object) public void add(Object anObject); // pre: anObject is non-null // post: the object is added to the collection at the // appropriate position based on comparing it to the // other elements. int index; index = this.indexOf ((Comparable) anObject); this.data.insertElementAt(anObject, index); } code based on Bailey pg. 176

©Duane Szafron OrderedVector - remove(Object) public Object remove(Object anObject); // pre: anObject is non-null // post: removes object “equal” to anObject and returns it, // otherwise returns nil int index; Object result; index = this.indexOf((Comparable) anObject)); if (index < this.size()) && (this.data.elementAt(index).equals(anObject)) { result = this.data.elementAt(index); //finds this.data.removeElementAt(index); //removes return result; } return null; } code based on Bailey pg. 177

©Duane Szafron OrderedVector - elements() public Iterator elements(); // post: return an iterator for traversing the collection return this.data.elements(); } code based on Bailey pg. 177

©Duane Szafron The Search Problem To complete this class, we need to solve the search problem for a sorted container. Given a container, find the index of a particular element, called the key. If it is not there, find the index where it should be ?

©Duane Szafron Binary Search Algorithm LHM middle = (low + high) / LHM low = middle + 1 middle = (low + high) / middle = (low + high) / 2 high = middle - 1 HML

©Duane Szafron Element not found 1 LHM middle = (low + high) / middle = (low + high) / 2 high = middle - 1 HML LHM low = middle + 1 middle = (low + high) /

©Duane Szafron Element not found 2 H low < high middle = (low + high) / 2 LM low = middle + 1 LHM

©Duane Szafron Element past end 1 LHM middle = (low + high) / middle = (low + high) / 2 HML low = middle + 1 LHM middle = (low + high) /

©Duane Szafron Element past end 2 H low < high middle = (low + high) / 2 LM low = middle + 1 LHM

©Duane Szafron OrderedVector - indexOf(Object) 1 /* Protected Methods */ protected int indexOf(Comparable anObject) { // pre: anObject is non-null // post: returns index of object in the collection or where // it should be placed if it is not in the collection Comparable midObject; int low; int high; int middle; int comparison; low = 0; high = this.data.size(); middle = (low + high) / 2; code based on Bailey pg. 174

©Duane Szafron OrderedVector - indexOf(Object) 2 while (low < high) { midObject = (Comparable) this.data.elementAt(middle); comparison = midObject.compareTo(anObject); if (comparison) < 0) low = middle + 1; else if (comparison > 0) high = middle - 1; else return middle; middle = (low + high) / 2; } return low; } code based on Bailey pg. 174

©Duane Szafron Time Complexity of OrderedVector The indexOf(Object) method does O(log(n)) comparisons to find the index. This means that it takes O(log(n)) comparisons for the add(Object), remove(Object) and contains(Object) methods. However, it also requires O(n) assignments to move elements in methods add(Object) and remove(Object). In Java, for most objects, the compareTo(Comparable) method is slower than assignment so the time complexity of add(Object) and remove(Object) is O(log(n)).

©Duane Szafron OrderedList We can also implement the OrderedStructure Interface using a linked list in a class called OrderedList. However, we do not simply bind an instance variable to a linked list object like a SinglyLinkedList since we require access to the middle of the list to put added elements in the correct location. Therefore we use SinglyLinkedListElements and link them together manually.

©Duane Szafron OrderedList - difference from OrderedVector The important difference between OrderedList and OrderedVector is that the internal implementation of OrderedVector has access to the indexes of the underlying Vector elements. –This allows us to find the index of a particular element so that it can be found, added, or removed. –It also allows us to do a binary search since we can divide the search list in half using the indexes.

©Duane Szafron OrderedList - Sequential Search In OrderedList, we create an analog of the indexOf(Object) method called previousOf(Object) which returns the node before the node containing the object, or the node before the node where the object should be inserted. Unfortunately, we must do a sequential search instead of a binary search. However, we can stop early if we encounter an element that is larger than the one we are looking for.

©Duane Szafron OrderedList - State and Constructor class OrderedList implements OrderedStructure { protected SinglyLinkedListElement head; protected int count; public OrderedList(){ // post: intitalizes the OrderedList to have 0 elements this.clear(); } code based on Bailey pg. 180

©Duane Szafron OrderedList - Store Interface /* Interface Store Methods */ public int size() { //post: returns the number of elements in the store. return this.count; } public boolean isEmpty() { // post: returns the true iff store is empty. return this.size() == 0; } public void clear(); // post: clears the store so that it contains no elements. this.head = null; this.count = 0; } code based on Bailey pg. 180

©Duane Szafron OrderedList - contains(Object) /* Interface Collection Methods */ public boolean contains(Object anObject) { // pre: anObject is non-null // post: returns true iff the collection contains the object SinglyLinkedListElement previous; SinglyLinkedListElement current; previous = this.previousOf((Comparable) anObject); if (previous == null) // no previous element, first node current = this.head; else current = previous.next(); if (current == null) return false; else return current.value().equals(anObject); } code based on Bailey pg. 180

©Duane Szafron OrderedList - add(Object) public void add(Object anObject); // pre: anObject is non-null // post: the object is added at the appropriate position // based on comparing it to the other elements. SinglyLinkedListElement previous; SinglyLinkedListElement current; Comparable comparable; previous = this.previousOf((Comparable) anObject); if (previous == null) // no previous element, first node this.head = new SinglyLinkedListElement(anObject, this.head); else previous.setNext(new SinglyLinkedListElement( anObject, previous.next())); this.count++; } code based on Bailey pg. 181

©Duane Szafron OrderedList - remove(Object) 1 public Object remove(Object anObject); // pre: anObject is non-null // post: removes object “equal” to anObject and returns it, // otherwise returns null SinglyLinkedListElement previous; SinglyLinkedListElement current; Comparable comparable; previous = this.previousOf((Comparable) anObject); if (previous == null) // no previous element, first node current = this.head; else current = previous.next(); if ((current == null) || !current.value().equals(anObject)) return null; code based on Bailey pg. 182

©Duane Szafron OrderedList - remove(Object) 2 if (previous == null) // no previous element, first node this.head = current.next(); else previous.setNext(current.next()); this.count--; } code based on Bailey pg. 182

©Duane Szafron OrderedList - elements() public Iterator elements(); // post: return an iterator for traversing the collection return new SinglyLinkedListIterator(this.head); } code based on Bailey pg. 182

©Duane Szafron OrderedList - previousOf(Object) 1 /* Protected Methods */ protected SinglyLinkedListElement previousOf(Object anObject) { // pre: anObject is non-null // post: returns the node before the node that contains the // given object, if the object is in the collection or the // node before where it should be placed if it is not in the collection SinglyLinkedListElement cursor; SinglyLinkedListElement previous; Comparable key; cursor = this.head; previous = null; key = (Comparable) anObject; code based on Bailey pg. 181

©Duane Szafron OrderedList - previousOf(Object) 2 while ((cursor != null) && (((Comparable) cursor.value()).compareTo(key) < 0)) { previous = cursor; cursor = cursor.next(); } return previous; } code based on Bailey pg. 181

©Duane Szafron Some Principles from the Textbook 16. Declare parameters of overriding methods with the most general types possible. (e.g., equals) 17. Avoid multiple casts of the same object by assigning the value to a temporary variable. 18. Consider your code from different points of view. principles from Bailey ch. 9