# Chapter 9 Part 2 Polymorphism Sorting Searching Outline

• Slides: 25

Chapter 9 – Part 2 Polymorphism: Sorting & Searching

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 30 3

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. © 2004 Pearson Addison-Wesley. All rights reserved 30 • Next (second pass), compare second to third, second to fourth…) 4

Selection Sort • An example: original: smallest is 1: 2: 3: 6: 3 1 1 9 9 2 2 2 6 6 6 3 3 1 3 3 6 6 2 2 9 9 9 • 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 30 5

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

Polymorphism in Sorting • Recall that a class that implements the Comparable interface defines a compare. To 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 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© 2004 method can be used to 30 sort a group of People, Pearson Addison-Wesley. All rights reserved or Books, or whatever – objects! 7

Selection Sort • The sorting method doesn't "care" what it is sorting, it just needs to be able to call the compare. To method to determine ‘how’ to compare. • That is guaranteed by using Comparable as the parameter type • 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: Phone. List. java, Sorting. java, and Contact. java (from your textbook) © 2004 Pearson Addison-Wesley. All rights reserved 30 8

// Phone. List. java Author: Lewis/Loftus // Driver for testing a sorting algorithm. //********************************** public class Phone. List { // 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"); Ditto. Actually creates friends[3] = new Contact ("Laura", "Getz", "663 -555 -3984"); seven objects and places friends[4] = new Contact ("Larry", "Smith", "464 -555 -3489"); references to each of these friends[5] = new Contact ("Frank", "Phelps", "322 -555 -2284"); objects into the friends array. 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. selection. Sort(friends); // NOTE: invokes the static method, select. Sort - 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; © 2004 Pearson Addison-Wesley. All rights reserved 30 System. out. println (friend); } 9

// 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 selection. Sort (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++) Selection Sort { (static method) min = index; for (int scan = index+1; scan < list. length; scan++) if (list[scan]. compare. To(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 selection. Sort // Sorts the specified array of objects using the insertion sort algorithm. public static void insertion. Sort (Comparable[] list) Another static method for independent use. { later…. 2004 Pearson Addison-Wesley. All rights reserved 30 Comparable© key = list[index]; more later…. Cut at this time… 10

//********************************** // 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 first. Name, last. Name, phone; // Constructor: Sets up this contact with the specified data. public Contact (String first, String last, String telephone) { first. Name = first; last. Name = last; phone = telephone; } // Returns a description of this contact as a string. public String to. String () //to. String for printing the object { return last. Name + ", " + first. Name + "t" + phone; } // Constructor 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 Last. Names and both First. Names are equal. // Returns a description of this contact as a string. public boolean equals (Object other) Here is the abstract method that MUST be implemented!!!! { Complicated. Comparing last. Name of this return (last. Name. equals(((Contact)other). get. Last. Name()) && object with the last name of the object passed first. Name. equals(((Contact)other). get. First. Name())); as a parameter. Note the cast because we are } © 2004 Pearson Addison-Wesley. All rights reserved 30 NOT defaulting to the generic Object – rather a Contact object. Hence the cast. 11

// Uses both last and first names to determine ordering. public int compare. To (Object other) // The other method that must be implemented!!! { This is implementation of compare. To int result; String other. First = ((Contact)other). get. First. Name(); String other. Last = ((Contact)other). get. Last. Name(); if (last. Name. equals(other. Last)) result = first. Name. compare. To(other. First); else result = last. Name. compare. To(other. Last); return result; } // First name accessor. public String get. First. Name () { return first. Name; } // end get. First. Name() // Last name accessor. public String get. Last. Name () { return last. Name; © 2004 Pearson Addison-Wesley. All rights reserved } // end get. Last. Name() } // end class (from last page) 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 (First. Name 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 get. First. Name() and get. Last. Name() are required to get a value that is compared to other. First is the passed parameter, the get… are for ‘this’ object. Note: this compare. To requires the use of an ‘equals’ method and NOT the default equals method of Object – hence the need to define our own (previous slide). 30 12

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 30 13

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

// 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 selection. Sort (Comparable[] list) { … already discussed. Cut here…. Cut out for this slide. } // end outer for Already discussed previously. // Sorts the specified array of objects using the insertion sort algorithm. public static void insertion. Sort (Comparable[] list) Here is the static method insertion. Sort() { for (int index = 1; index < list. length; index++) { Comparable key = list[index]; body of insertion. Sort() int position = index; Same idea as selection. Sort() // Shift larger values to the right while (position > 0 && key. compare. To(list[position-1]) < 0) We will not go through this, { but the code is available for list[position] = list[position-1]; use… position--; } list[position] = key; 30 }// end for © 2004 Pearson Addison-Wesley. All rights reserved } // end insertion. Sort method 15 } // end class Sorting

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 30 16

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 30 18

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 30 19

// Phone. List 2. java Author: Lewis/Loftus Driver for testing searching algorithms. public class Phone. List 2 { // 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; Creates an array of references, Contact[] friends = new Contact[8]; as usual and then creates the friends[0] = new Contact ("John", "Smith", "610 -555 -7384"); friends[1] = new Contact ("Sarah", "Barnes", "215 -555 -3827"); individual objects with references friends[2] = new Contact ("Mark", "Riley", "733 -555 -2969"); in the array of references, friends[3] = new Contact ("Laura", "Getz", "663 -555 -3984"); Nothing new here… 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"); Search argument. friends[7] = new Contact ("Marsha", "Grant", "243 -555 -2837"); Could come from any test = new Contact ("Frank", "Phelps", ""); source! Object created. if found, found = (Contact) Searching. linear. Search(friends, test); print msg if (found != null) System. out. println ("Found: " + found); plus object Call to linear. Search(). Passes otherwise, else two parameters: the array of System. out. println ("The contact was not found. "); print not references, friends, and found msg. System. out. println (); the search argument object, test. code for binary search removed. Will see in later slide…. }// end main() } // end Phone. List 2 Note the if(found!= null). © 2004 Pearson Addison-Wesley. All rights reserved 30 linear. Search() returns a pointer to target or else null, if not found. 20

//********************************** // 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 linear. Search (Comparable[] list, Comparable target) { int index = 0; boolean found = false; while (!found && index < list. length) { if (list[index]. equals(target)) found = true; else index++; } 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 if (found) by these special objects… return list[index]; else return null; }// end linear. Search() (static method). binary. Search() (in same class) is cut from this slide. Will see later. public static Comparable binary. Search (Comparable[] list, Comparable target) © 2004 Pearson Addison-Wesley. All rights reserved 30 etc. 21

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 30 22

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 Phone. List 2. java and Searching. java (page 509), specifically the binary. Search method © 2004 Pearson Addison-Wesley. All rights reserved 30 23

// Phone. List 2. java Author: Lewis/Loftus Driver for testing searching algorithms. public class Phone. List 2 { // Creates an array of Contact objects, sorts them, then prints them. public static void main (String[] args) { Same as previous slide Contact test, found; Contact[] friends = new Contact[8]; but here we will concentrate on friends[0] = new Contact ("John", "Smith", "610 -555 -7384"); the binary search. 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"); Note these searches are using friends[4] = new Contact ("Larry", "Smith", "464 -555 -3489"); static methods, hence the class friends[5] = new Contact ("Frank", "Phelps", "322 -555 -2284"); name dot method name. friends[6] = new Contact ("Mario", "Guzman", "804 -555 -9066"); The (Contact) types the return friends[7] = new Contact ("Marsha", "Grant", "243 -555 -2837"); test = new Contact ("Frank", "Phelps", ""); to be compatible with ‘found’. found = (Contact) Searching. linear. Search(friends, test); if (found != null) System. out. println ("Found: " + found); Sequential Search. Ignore this example. else System. out. println ("The contact was not found. "); Binary Search. Must have search space System. out. println (); sorted. Hence the selection. Sort(friends) Sorting. selection. Sort(friends); test = new Contact ("Mario", "Guzman", ""); Need search argument – always. (test) found = (Contact) Searching. binary. Search(friends, test); This is ‘call’ to binary. Search() method. if (found != null) System. out. println ("Found: " + found); else © 2004 Pearson Addison-Wesley. All rights reserved 30 System. out. println ("The contact was not found. "); } 24 }

// 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 linear. Search (Comparable[] list, Comparable target) }// cut Comparable linear. Search(). public static Comparable binary. Search (Comparable[] list, Comparable target) { int min=0, max=list. length, mid=0; Here’s boolean found = false; our binary. Serarch() routine. while (!found && min <= max) { mid = (min+max) / 2; if (list[mid]. equals(target)) found = true; else if (target. compare. To(list[mid]) < 0) max = mid-1; else min = mid+1; } if (found) return list[mid]; © 2004 Pearson Addison-Wesley. All rights reserved else return null; } Again, the binary. Search() uses the compare. To() routine and an equals() routine, as before… 30 Since we are using objects of the same type, the same implementation of compare. To and the overriding of equals apply. 25