chapter 9 – part 2 polymorphism: sorting & searching

25
Chapter 9 – Part 2 Polymorphism: Sorting & Searching

Upload: emmeline-barton

Post on 01-Jan-2016

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

Chapter 9 – Part 2

Polymorphism: Sorting & Searching

Page 2: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-2

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching

Page 3: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-3

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

Page 4: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-4

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…)

Page 5: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-5

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

Page 6: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-6

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.)

Page 7: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-7

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

• The sorting method accepts as a parameterparameter an array of Comparable objectsobjects

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!

Page 8: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-8

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

Also, in this manner, each class decideseach 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)

Page 9: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-9

// 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 placesreferences to each of theseobjects into the friends array.

Page 10: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-10

// 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(staticstatic method)

later….

Page 11: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-11

//********************************************************************// 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 mustoverride to define our own – specifically, what determineswhen two objects are ‘equal.’Decision: when both LastNamesand both FirstNames are equal.

Complicated. Comparing lastName of thisobject with the last name of the object passedas a parameter. Note the cast because we are NOT defaulting to the generic Object – rathera Contact object. Hence the cast.

Page 12: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-12

// 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 compareTowhich is an abstract method in theComparable interface.Same rationale as for ‘equals’ (previousslide). We are defining HOW to compare attributes of ‘this’ object withspecific attributes (FirstName and LastName) of the object passed as a parameter.

We need the cast operator to identify whichobject type (Contact) we are comparing.Note the getFirstName() and getLastName()are required to get a value that is comparedto otherFirst. otherFirst is the passedparameter, the get… are for ‘this’ object.

Note: this compareTo requires the use of an‘equals’ method and NOT the defaultequals method of Object – hence the need todefine our own (previous slide).

Page 13: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-13

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

Page 14: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-14

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

Page 15: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-15

// 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 foruse…

Page 16: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-16

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 n2 number of comparisons are made to sort a list of size n

We therefore say that these sorts are of order n2

• Other sorts are more efficient: Order n log2 n. These are normally written in ‘big O notation’ as: O(n log2 n).

Page 17: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-17

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching

Page 18: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-18

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

Page 19: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-19

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

Page 20: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-20

// 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 referencesin the array of references, friends.Nothing new here…

Search argument.Could come from anysource! Object created.

Call to linearSearch(). Passestwo parameters: the array of references, friends, and the search argument object, test.

Note the if(found!= null).linearSearch() returns a pointerto target or else null, if not found.

if found, print msg plus objectotherwise,print notfound msg.

Page 21: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-21

//********************************************************************// 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 Comparableobjects, list (actually references) and anobject (target) of type Comparable.

So, we need to define how ‘equality’ is coveredby these special objects…

Page 22: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-22

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

Page 23: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-23

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

Page 24: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-24

// 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 slidebut here we will concentrate onthe binary search.

Note these searches are usingstatic methods, hence the classname dot method name.The (Contact) types the returnto be compatible with ‘found’.

Sequential Search. Ignore this example.

Binary Search. Must have search spacesorted. Hence the selectionSort(friends)Need search argument – always. (test)This is ‘call’ to binarySearch() method.

Page 25: Chapter 9 – Part 2 Polymorphism: Sorting & Searching

© 2004 Pearson Addison-Wesley. All rights reserved 30

9-25

// 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() routineand an equals() routine,as before…

Since we are using objects ofthe same type, the same implementation of compareToand the overriding of equalsapply.