Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 – Part 2 Polymorphism: Sorting & Searching.

Similar presentations


Presentation on theme: "Chapter 9 – Part 2 Polymorphism: Sorting & Searching."— Presentation transcript:

1 Chapter 9 – Part 2 Polymorphism: Sorting & Searching

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

3 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-3 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)

4 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-4 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();

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

6 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-6 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

7 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-7 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…)

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

9 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-9 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.)

10 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-10 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!

11 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-11 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)

12 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-12 // 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", "610-555-7384"); // Above: Creates new object and ensures friends[0] points to this new object. friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827"); friends[2] = new Contact ("Mark", "Riley", "733-555-2969"); friends[3] = new Contact ("Laura", "Getz", "663-555-3984"); friends[4] = new Contact ("Larry", "Smith", "464-555-3489"); friends[5] = new Contact ("Frank", "Phelps", "322-555-2284"); friends[6] = new Contact ("Mario", "Guzman", "804-555-9066"); friends[7] = new Contact ("Marsha", "Grant", "243-555-2837"); // 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.

13 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-13 // 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….

14 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-14 //******************************************************************** // 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.

15 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-15 // 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).

16 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-16 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

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

18 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-18 // 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…

19 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-19 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).

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

21 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-21 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

22 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-22 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

23 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-23 // 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", "610-555-7384"); friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827"); friends[2] = new Contact ("Mark", "Riley", "733-555-2969"); friends[3] = new Contact ("Laura", "Getz", "663-555-3984"); friends[4] = new Contact ("Larry", "Smith", "464-555-3489"); friends[5] = new Contact ("Frank", "Phelps", "322-555-2284"); friends[6] = new Contact ("Mario", "Guzman", "804-555-9066"); friends[7] = new Contact ("Marsha", "Grant", "243-555-2837"); 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.

24 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-24 //******************************************************************** // 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…

25 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-25 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

26 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-26 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

27 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-27 // 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", "610-555-7384"); friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827"); friends[2] = new Contact ("Mark", "Riley", "733-555-2969"); friends[3] = new Contact ("Laura", "Getz", "663-555-3984"); friends[4] = new Contact ("Larry", "Smith", "464-555-3489"); friends[5] = new Contact ("Frank", "Phelps", "322-555-2284"); friends[6] = new Contact ("Mario", "Guzman", "804-555-9066"); friends[7] = new Contact ("Marsha", "Grant", "243-555-2837"); 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.

28 © 2004 Pearson Addison-Wesley. All rights reserved 30 9-28 // 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.


Download ppt "Chapter 9 – Part 2 Polymorphism: Sorting & Searching."

Similar presentations


Ads by Google