Chapter 9 – Part 2
Polymorphism: Sorting & Searching
Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces
Sorting
Searching
© 2004 Pearson Addison-Wesley. All rights reserved
30
9-2
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
9-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.
30
• Next (second pass), compare second to third, second to fourth…)
© 2004 Pearson Addison-Wesley. All rights reserved
9-4
Selection Sort
• An example:
original:
smallest is
smallest is
smallest is
smallest is
1:
2:
3:
6:
3
1
1
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
9-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.)
9-6
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 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 to30sort a group of People,
Pearson Addison-Wesley. All rights reserved
or Books, or whatever – objects!
9-7
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 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
30
9-8
// 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");
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.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;
© 2004 Pearson Addison-Wesley. All rights reserved
30
System.out.println (friend);
}
9-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 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++)
Selection Sort
{
(static method)
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.
{
later….
2004 Pearson
Addison-Wesley. All rights reserved
30
Comparable© key
= list[index];
more later…. Cut at this time…
9-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 firstName, lastName, phone;
// Constructor: Sets up this contact with the specified data.
public Contact (String first, String last, String telephone)
{
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;
}
// 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 LastNames
and both FirstNames 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 lastName of this
return (lastName.equals(((Contact)other).getLastName()) &&
object with the last name of the object passed
firstName.equals(((Contact)other).getFirstName()));
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.
9-11
// Uses both last and first names to determine ordering.
public int compareTo (Object other) //  The other method that must be implemented!!!
{
This is implementation of compareTo
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;
© 2004 Pearson Addison-Wesley. All rights reserved
} // end getLastName()
} // 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 (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
30 our own (previous slide).
9-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
9-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
2
2
9
• See Sorting.java (page 501), specifically the
insertionSort method
© 2004 Pearson Addison-Wesley. All rights reserved
30
9-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 selectionSort (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 insertionSort (Comparable[] list)  Here is the static method insertionSort()
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
body of insertionSort()
int position = index;
Same idea as selectionSort()
// Shift larger values to the right
while (position > 0 && key.compareTo(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 insertionSort method
9-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 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).
© 2004 Pearson Addison-Wesley. All rights reserved
30
9-16
Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces
Sorting
Searching
© 2004 Pearson Addison-Wesley. All rights reserved
30
9-17
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
9-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
9-19
// 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;
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.
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.linearSearch(friends, test);
print msg if (found != null)
System.out.println ("Found: " + found);
plus object
Call to linearSearch(). 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 PhoneList2
Note the if(found!= null).
linearSearch() returns a pointer
to target or else null, if not found.
© 2004 Pearson Addison-Wesley. All rights reserved
30
9-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 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++;
}
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 linearSearch() (static method). binarySearch() (in same class) is cut from this slide. Will see later.
public static Comparable binarySearch (Comparable[] list, Comparable target)
© 2004 Pearson Addison-Wesley. All rights reserved
30
etc. etc.
9-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
9-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 PhoneList2.java and Searching.java
(page 509), specifically the binarySearch method
© 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)
{
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.linearSearch(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 selectionSort(friends)
Sorting.selectionSort(friends);
test = new Contact ("Mario", "Guzman", "");
Need search argument – always. (test)
found = (Contact) Searching.binarySearch(friends, test);
This is ‘call’ to binarySearch() 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.");
}
9-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 linearSearch (Comparable[] list, Comparable target)
}// cut Comparable linearSearch().
public static Comparable binarySearch (Comparable[] list, Comparable target)
{
int min=0, max=list.length, mid=0;
Here’s
boolean found = false;
our binarySerarch()
routine.
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];
© 2004 Pearson Addison-Wesley. All rights reserved
else
return null;
}
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.
30
9-25