Professional Documents
Culture Documents
Part 2: Polymorphism: Sorting & Searching
Part 2: Polymorphism: Sorting & Searching
Outline
Polymorphic References
Polymorphism via Inheritance
30
9-2
Speaker current;
Reference to
Interface, Speaker
(recall, Interface
cannot be instantiated)
current.speak();
2004 Pearson Addison-Wesley. All rights reserved
30
9-3
30
9-4
Outline
Polymorphic References
Polymorphism via Inheritance
30
9-5
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
30
9-6
Selection Sort
The approach of Selection Sort:
select a value and put it in its final place into the list
In more detail:
find the smallest value in the list
9-7
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
30
9-8
Swapping
The processing of the selection sort algorithm
includes the swapping of two values
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.)
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
30
9-11
// 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 listagain, 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-12
// 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-13
//********************************************************************
// 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
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)
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-16
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
30
9-17
// 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-18
} // end class Sorting
Comparing Sorts
The Selection and Insertion sort algorithms are similar
in efficiency
30
9-19
Outline
Polymorphic References
Polymorphism via Inheritance
30
9-20
Searching
Searching is the process of finding a target element
within a group of items called the search pool
30
9-21
Linear Search
A linear search begins at one end of a list and
examines each element in turn
30
9-22
// 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).
30
9-23
//********************************************************************
// 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)
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-24
Binary Search
A binary search assumes the list of items in the
search pool is sorted
30
9-25
Binary Search
The process continues by comparing the middle
element of the remaining viable candidates
30
9-26
// 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-27
}
// 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;
Heres
boolean found = false;
our binarySerarch()
routine.