Chapter 9 – Part 2 Polymorphism: Sorting & Searching.

Slides:



Advertisements
Similar presentations
Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
Advertisements

CSE Lecture 3 – Algorithms I
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Abstract Classes  An abstract class is a placeholder in a class hierarchy that represents a generic concept  An abstract class cannot be instantiated.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Polymorphism Polymorphism (having many forms) is an object- oriented concept.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Chapter Day 22. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 22 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21 (right.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Algorithm Efficiency and Sorting
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Chapter 18 Searching and Sorting
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
Aalborg Media Lab 15-Jul-15 Polymorphism Lecture 12 Chapter 9.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
EFFICIENCY & SORTING CITS1001. Listen to the sound of sorting Various algorithms Quicksort
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Do Now Take out ch6 test answers – be ready to hand it in Pick a leader in each group of up to 3 students; Leader will retrieve a whiteboard, marker, and.
Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 8: Sorting and Searching Java Software Structures: Designing.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
Chapter 9 – Part 2 Polymorphism: Sorting & Searching.
Chapter 9 Searching and Sorting
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
CSCI 51 Introduction to Programming March 12, 2009.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
ELC 310 Day 19. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Agenda Questions? Capstone Proposals Overdue  4 Submitted  3 Accepted, 1 in negotiations.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
1 Sorting b Sorting is the process of arranging a list of items into a particular order b There must be some value on which the order is based b There.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
ArrayList is a class that implements the List interface. The List interface is a blueprint for its “implementor” classes. There is another implementor.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
CSCI 51 Introduction to Programming March 10, 2009.
Sequential (Linear) Binary Selection** Insertion** Merge.
Searching and Sorting Searching algorithms with simple arrays
Chapter 9: Sorting and Searching Arrays
Chapter 12 Recursion.
Chapter 9 Polymorphism.
Chapter 13: Searching and Sorting
Sorts.
Data Structures and Algorithms
Outline Late Binding Polymorphism via Inheritance
Sorting and Searching -- Introduction
Module 8 – Searching & Sorting Algorithms
Arrays.
Presentation transcript:

Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching

© 2004 Pearson Addison-Wesley. All rights reserved Polymorphism via Interfaces An interface name can be used as the type of an ‘object reference variable’ (Remember, an ‘interface’ is not a class…) Speaker current; The current reference can be used to point to any object class Speaker or any class that implements the Speaker interface The version of speak that the following line invokes depends on the type of object that current is referencing (that is, “which” class that ‘implements’ Speaker…) current.speak(); Reference to Interface, Speaker (recall, Interface cannot be instantiated)

© 2004 Pearson Addison-Wesley. All rights reserved Polymorphism via Interfaces Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method In the following code, the first call to speak invokes one version and the second invokes another: Speaker guest; (guest is a reference to Speaker) guest = new Philospher(); guest.speak(); guest = new Dog(); guest.speak();

© 2004 Pearson Addison-Wesley. All rights reserved Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching

© 2004 Pearson Addison-Wesley. All rights reserved Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s)  sorting a list of test scores in ascending numeric order  sorting a list of people alphabetically by last name There are many algorithms, which vary in efficiency, for sorting a list of items Some are very good under certain circumstances and provide very poor results in other circumstances. None are always the best or always the poorest! We will examine two specific algorithms:  Selection Sort  Insertion Sort

© 2004 Pearson Addison-Wesley. All rights reserved Selection Sort The approach of Selection Sort:  select a value and put it in its final place into the list  repeat for all other values  In more detail:  find the smallest value in the list  switch it with the value in the first position  find the next smallest value in the list  switch it with the value in the second position  repeat until all values are in their proper places (Compare the first to the second; switch if second is smaller. Compare new first to third; switch if needed; compare first to fourth, …compare first to last. Iterate. Next (second pass), compare second to third, second to fourth…)

© 2004 Pearson Addison-Wesley. All rights reserved Selection Sort An example: original: smallest is 1: smallest is 2: smallest is 3: smallest is 6: Each time, the smallest remaining value is found and exchanged with the element in the "next" position to be filled

© 2004 Pearson Addison-Wesley. All rights reserved Swapping The processing of the selection sort algorithm includes the swapping of two values Swapping requires three assignment statements and a temporary storage location: temp = first; first = second; second = temp; ( Not too terribly inefficient ‘ for small n. ’ Lots of compares (n-squared), but generally not too many ‘swaps.’) (For large ‘n’, this normally gives very poor performance.)

© 2004 Pearson Addison-Wesley. All rights reserved Polymorphism in Sorting Recall that a class that implements the Comparable interface defines a compareTo method to determine the relative order of its objects. (See text, if forgotten.)  We can use polymorphism to develop a generic sort for any set of Comparable objects parameter objectsThe sorting method accepts as a parameter an array of Comparable objects  When we say an array of Comparable objects, we mean that the class of objects MUST implement the Comparable interface!  This means that the class must contain a method that defines HOW objects of ‘that class’ are to be compared! So, one method can be used to sort a group of People, or Books, or whatever – objects!

© 2004 Pearson Addison-Wesley. All rights reserved Selection Sort The sorting method doesn't "care" what it is sorting, it just needs to be able to call the compareTo method to determine ‘how’ to compare. That is guaranteed by using Comparable as the parameter type each class decides  Also, in this manner, each class decides for itself what it means for one object to be less than another, as stated. Let’s look at three modules: PhoneList.java, Sorting.java, and Contact.java (from your textbook)

© 2004 Pearson Addison-Wesley. All rights reserved // PhoneList.java Author: Lewis/Loftus // Driver for testing a sorting algorithm. //******************************************************************** public class PhoneList { // Creates an array of Contact objects, sorts them, then prints them. public static void main (String[] args) { Contact[] friends = new Contact[8]; // creates an array of references of size 8. (no addresses yet…) friends[0] = new Contact ("John", "Smith", " "); // Above: Creates new object and ensures friends[0] points to this new object. friends[1] = new Contact ("Sarah", "Barnes", " "); friends[2] = new Contact ("Mark", "Riley", " "); friends[3] = new Contact ("Laura", "Getz", " "); friends[4] = new Contact ("Larry", "Smith", " "); friends[5] = new Contact ("Frank", "Phelps", " "); friends[6] = new Contact ("Mario", "Guzman", " "); friends[7] = new Contact ("Marsha", "Grant", " "); // So we have an array of references, friends, each of which points to one of eight objects. Sorting.selectionSort(friends); // NOTE: invokes the static method, selectSort - feeds it ‘friends’ as // an argument; ‘friends’ must be a comparable list…again, means Contact // must ‘implement’ the Comparable interface which means Contact must // totally define ‘compare to’ method and ‘equal’ for (Contact friend : friends) //This simply uses the iterator form of the ‘for’ to print sorted array; System.out.println (friend); } Ditto. Actually creates seven objects and places references to each of these objects into the friends array.

© 2004 Pearson Addison-Wesley. All rights reserved // Sorting.java Author: Lewis/Loftus Demonstrates the selection sort and insertion sort algorithms. public class Sorting { // Sorts the specified array of objects using the selection sort algorithm public static void selectionSort (Comparable[] list)  Note: static class. Think Mathclass of {// static methods….Note: formal parameter!!! int min; Comparable temp; // a reference to a single object for (int index = 0; index < list.length-1; index++) { min = index; for (int scan = index+1; scan < list.length; scan++) if (list[scan].compareTo(list[min]) < 0) min = scan; // Note: this stores only the index of the smallest item. // After traversing the list, we now swap the values based on the stored indiex of the //smallest item above. temp = list[min]; list[min] = list[index]; list[index] = temp; } // end for // now iterate for the next item in the list… } // end selectionSort // Sorts the specified array of objects using the insertion sort algorithm. public static void insertionSort (Comparable[] list)  Another static method for independent use. { Comparable key = list[index]; more later…. Cut at this time… Selection Sort static (static method) later….

© 2004 Pearson Addison-Wesley. All rights reserved //******************************************************************** // Contact.java Author: Lewis/Loftus Represents a phone contact. //******************************************************************** public class Contact implements Comparable  Here is the ‘implementation of the Comparable Interface!! //  Note: Contact ‘implements’ the Comparable Interface. thus must define: equals!!! { private String firstName, lastName, phone; // Constructor: Sets up this contact with the specified data. public Contact (String first, String last, String telephone) // Constructor { firstName = first; lastName = last; phone = telephone; } // Returns a description of this contact as a string. public String toString () //toString for printing the object { return lastName + ", " + firstName + "\t" + phone; } // Returns a description of this contact as a string. public boolean equals (Object other)  Here is the abstract method that MUST be implemented!!!! { return (lastName.equals(((Contact)other).getLastName()) && firstName.equals(((Contact)other).getFirstName())); } This method overrides the ‘equals’ method inherited from Object. We must override to define our own – specifically, what determines when two objects are ‘equal.’ Decision: when both LastNames and both FirstNames are equal. Complicated. Comparing lastName of this object with the last name of the object passed as a parameter. Note the cast because we are NOT defaulting to the generic Object – rather a Contact object. Hence the cast.

© 2004 Pearson Addison-Wesley. All rights reserved // Uses both last and first names to determine ordering. public int compareTo (Object other) //  The other method that must be implemented!!! { int result; String otherFirst = ((Contact)other).getFirstName(); String otherLast = ((Contact)other).getLastName(); if (lastName.equals(otherLast)) result = firstName.compareTo(otherFirst); else result = lastName.compareTo(otherLast); return result; } // First name accessor. public String getFirstName () { return firstName; } // end getFirstName() // Last name accessor. public String getLastName () { return lastName; } // end getLastName() } // end class (from last page) This is implementation of compareTo which is an abstract method in the Comparable interface. Same rationale as for ‘equals’ (previous slide). We are defining HOW to compare attributes of ‘this’ object with specific attributes (FirstName and Last Name) of the object passed as a parameter. We need the cast operator to identify which object type (Contact) we are comparing. Note the getFirstName() and getLastName() are required to get a value that is compared to otherFirst. otherFirst is the passed parameter, the get… are for ‘this’ object. Note: this compareTo requires the use of an ‘equals’ method and NOT the default equals method of Object – hence the need to define our own (previous slide).

© 2004 Pearson Addison-Wesley. All rights reserved Insertion Sort The approach of Insertion Sort:  pick any item and insert it into its proper place in a sorted sublist  repeat until all items have been inserted In more detail:  consider the first item to be a sorted sublist (of one item)  insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition  insert the third item into the sorted sublist (of two items), shifting items as necessary  repeat until all values are inserted into their proper positions

© 2004 Pearson Addison-Wesley. All rights reserved Insertion Sort An example: original: insert 9: insert 6: insert 1: insert 2: See Sorting.java (page 501), specifically the insertionSort method Sorting.java

© 2004 Pearson Addison-Wesley. All rights reserved // Sorting.java Author: Lewis/Loftus Demonstrates the selection sort and insertion sort algorithms. public class Sorting { // Sorts the specified array of objects using the selection sort algorithm public static void selectionSort (Comparable[] list)  { … already discussed. Cut here…. } // end outer for // Sorts the specified array of objects using the insertion sort algorithm. public static void insertionSort (Comparable[] list)  Here is the static method insertionSort() { for (int index = 1; index < list.length; index++) { Comparable key = list[index]; int position = index; // Shift larger values to the right while (position > 0 && key.compareTo(list[position-1]) < 0) { list[position] = list[position-1]; position--; } list[position] = key; }// end for } // end insertionSort method } // end class Sorting Cut out for this slide. Already discussed previously. body of insertionSort() Same idea as selectionSort() We will not go through this, but the code is available for use…

© 2004 Pearson Addison-Wesley. All rights reserved Comparing Sorts The Selection and Insertion sort algorithms are similar in efficiency They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list  Approximately n 2 number of comparisons are made to sort a list of size n  We therefore say that these sorts are of order n 2 Other sorts are more efficient: Order n log 2 n. These are normally written in ‘big O notation’ as: O(n log 2 n).

© 2004 Pearson Addison-Wesley. All rights reserved Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching

© 2004 Pearson Addison-Wesley. All rights reserved Searching Searching is the process of finding a target element within a group of items called the search pool The target may or may not be in the search pool We want to perform the search efficiently, minimizing the number of comparisons  Let's look at two classic searching approaches: linear search (sometimes called a sequential search) and binary search As we did with sorting, we'll implement the searches with polymorphic Comparable parameters

© 2004 Pearson Addison-Wesley. All rights reserved Linear Search A linear search begins at one end of a list and examines each element in turn Eventually, either the item is found or the end of the list is encountered

© 2004 Pearson Addison-Wesley. All rights reserved // PhoneList2.java Author: Lewis/Loftus Driver for testing searching algorithms. public class PhoneList2 { // Creates an array of Contact objects, sorts them, then prints them. public static void main (String[] args) // Note: more utility routines developed as static methods… { Contact test, found; Contact[] friends = new Contact[8]; friends[0] = new Contact ("John", "Smith", " "); friends[1] = new Contact ("Sarah", "Barnes", " "); friends[2] = new Contact ("Mark", "Riley", " "); friends[3] = new Contact ("Laura", "Getz", " "); friends[4] = new Contact ("Larry", "Smith", " "); friends[5] = new Contact ("Frank", "Phelps", " "); friends[6] = new Contact ("Mario", "Guzman", " "); friends[7] = new Contact ("Marsha", "Grant", " "); test = new Contact ("Frank", "Phelps", ""); found = (Contact) Searching.linearSearch(friends, test); if (found != null) System.out.println ("Found: " + found); else System.out.println ("The contact was not found."); System.out.println (); code for binary search removed. Will see in later slide…. }// end main() } // end PhoneList2 Creates an array of references, as usual and then creates the individual objects with references in the array of references, friends. Nothing new here… Search argument. Could come from any source! Object created. Call to linearSearch(). Passes two parameters: the array of references, friends, and the search argument object, test. Note the if(found!= null). linearSearch() returns a pointer to target or else null, if not found. if found, print msg plus object otherwise, print not found msg.

© 2004 Pearson Addison-Wesley. All rights reserved //******************************************************************** // Searching.java Author: Lewis/Loftus // Demonstrates the linear search and binary search algorithms. //******************************************************************** public class Searching { // // Searches the specified array of objects for the target using a linear search. Returns a reference to the target object from the array if found, and null otherwise. public static Comparable linearSearch (Comparable[] list, Comparable target) { int index = 0; boolean found = false; while (!found && index < list.length) { if (list[index].equals(target)) found = true; else index++; } if (found) return list[index]; else return null; }// end linearSearch() (static method). binarySearch() (in same class) is cut from this slide. Will see later. public static Comparable binarySearch (Comparable[] list, Comparable target) etc. etc. Note: received an array of Comparable objects, list (actually references) and an object (target) of type Comparable. So, we need to define how ‘equality’ is covered by these special objects…

© 2004 Pearson Addison-Wesley. All rights reserved Binary Search A binary search assumes the list of items in the search pool is sorted It eliminates a large part of the search pool with a single comparison A binary search first examines the middle element of the list -- if it matches the target, the search is over If it doesn't, only one half of the remaining elements need be searched Since they are sorted, the target can only be in one half of the other

© 2004 Pearson Addison-Wesley. All rights reserved Binary Search The process continues by comparing the middle element of the remaining viable candidates Each comparison eliminates approximately half of the remaining data Eventually, the target is found or the data is exhausted See PhoneList2.java and Searching.java (page 509), specifically the binarySearch method PhoneList2.javaSearching.java

© 2004 Pearson Addison-Wesley. All rights reserved // PhoneList2.java Author: Lewis/Loftus Driver for testing searching algorithms. public class PhoneList2 { // Creates an array of Contact objects, sorts them, then prints them. public static void main (String[] args) { Contact test, found; Contact[] friends = new Contact[8]; friends[0] = new Contact ("John", "Smith", " "); friends[1] = new Contact ("Sarah", "Barnes", " "); friends[2] = new Contact ("Mark", "Riley", " "); friends[3] = new Contact ("Laura", "Getz", " "); friends[4] = new Contact ("Larry", "Smith", " "); friends[5] = new Contact ("Frank", "Phelps", " "); friends[6] = new Contact ("Mario", "Guzman", " "); friends[7] = new Contact ("Marsha", "Grant", " "); test = new Contact ("Frank", "Phelps", ""); found = (Contact) Searching.linearSearch(friends, test); if (found != null) System.out.println ("Found: " + found); else System.out.println ("The contact was not found."); System.out.println (); Sorting.selectionSort(friends); test = new Contact ("Mario", "Guzman", ""); found = (Contact) Searching.binarySearch(friends, test); if (found != null) System.out.println ("Found: " + found); else System.out.println ("The contact was not found."); } Same as previous slide but here we will concentrate on the binary search. Note these searches are using static methods, hence the class name dot method name. The (Contact) types the return to be compatible with ‘found’. Sequential Search. Ignore this example. Binary Search. Must have search space sorted. Hence the selectionSort(friends) Need search argument – always. (test) This is ‘call’ to binarySearch() method.

© 2004 Pearson Addison-Wesley. All rights reserved // Searching.java Author: Lewis/Loftus Demonstrates the linear search and binary search algorithms. //******************************************************************** public class Searching { // Returns a reference to the target object from the array if found, and null otherwise. // public static Comparable linearSearch (Comparable[] list, Comparable target) }// cut Comparable linearSearch(). public static Comparable binarySearch (Comparable[] list, Comparable target) { int min=0, max=list.length, mid=0; boolean found = false; while (!found && min <= max) { mid = (min+max) / 2; if (list[mid].equals(target)) found = true; else if (target.compareTo(list[mid]) < 0) max = mid-1; else min = mid+1; } if (found) return list[mid]; else return null; } Here’s our binarySerarch() routine. Again, the binarySearch() uses the compareTo() routine and an equals() routine, as before… Since we are using objects of the same type, the same implementation of compareTo and the overriding of equals apply.