[Instructions] [Search] [Current] [News] [Syllabus] [Glance] [Links] [Handouts] [Project] [Outlines] [Labs] [Assignments] [Quizzes] [Exams] [Examples] [EIJ] [JPDS] [Tutorial] [API]
Back to Introduction to Sorting. On to More Efficient Sorting Algorithms.
Held Tuesday, March 7, 2000
Overview
Today we continue our discussion of sorting by investigating two other simple sorting algorithms: bubble sort and selection sort. We also visit other issues in the design of sorting algorithms.
Notes
Contents
Summary
public void sortThyself(Comparator compare);
Comparator interface look like?
equals(Object,Object) method.
precedes(Object,Object) method.
/**
* Objects that can compare pairs of objects (for equality and
* ordering). We assume that if something is neither less than
* or equal to another object, then it is greater than that other
* object. Typically used to help with sorting.
*
* @author Samuel A. Rebelsky
* @version 1.2 of March 2000
*/
public interface Comparator {
/**
* Determine if the first element should precede the
* second. Throws an exception if the two elements cannot
* be compared.
*/
public boolean precedes(Object first, Object second)
throws IncomparableException;
/**
* Determine if the first element is equal to the second. Throws
* an exception if the two elements cannot be compared.
*/
public boolean equals(Object first, Object second)
throws IncomparableException;
} // interface Comparator
StudentInfo
class we were designing.
StudentNameComparator
StudentGradeComparator
StudnetIDComparator
import Comparator;
/**
* Compares two objects by considering their string representations.
* Does case-insensitive comparison. Particularly useful for
* comparing strings, but can also be used for other objects.
*
* @author Samuel A. Rebelsky
* @version 1.2 of March 2000
*/
public class StringComparator
implements Comparator
{
/**
* Determines if the string reperesentation of the first object
* is the same as the string representation of the second object.
* Pre: The two objects are initialized and can be converted to strings.
* Post: Returns true if they are equal and false otherwise.
*/
public boolean equals(Object first, Object second)
{
String firstString = first.toString().toLowerCase();
String secondString = second.toString().toLowerCase();
return firstString.equals(secondString);
} // equals(Object,Object)
/* Determines if the string representation of the first object
* should precede than the string representation of the second object.
* One string precedes another iff letters 0 through i-1
* of the two strings are the same and either (i) letter i of the
* first string is less than letter i of the second string or (ii)
* the first string has only i letters and the second string has more
* than i letters.
*/
public boolean precedes(Object first, Object second)
{
String firstString = first.toString().toLowerCase();
String secondString = second.toString().toLowerCase();
// The compareTo operator returns a negative value if
// the first string precedes the second.
return firstString.compareTo(secondString) < 0;
} // precedes(Object,Object)
} // class StringComparator
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
|
Unsorted Sorted
elementAt references are to ``the current object''.
import Array;
import Sortable;
/**
* Arrays that you can sort using selection sort.
*
* @author Samuel A. Rebelsky
* @version 1.0 of October 1999
*/
public class SelectionSortable
extends Array
implements Sortable
{
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new array which holds up to n elements.
* Initially, each element is null.
*/
public SelectionSortable(int n) {
super(n);
} // SelectionSortable(int)
/**
* Build a new array which holds the specified
* set of elements.
*/
public SelectionSortable(Object[] elements) {
super(elements);
} // SelectionSortable(Object[])
// +-----------------------+-----------------------------------
// | Methods from Sortable |
// +-----------------------+
/**
* Sort all the elements in the array using selection sort.
* Pre: the elements in the array are comparable using
* a lessEqual method.
* Post: elementAt(i) <= elementAt(i+1) for all 0 <= i < size()-1.
* Post: no element is added to or removed from the subarray.
* Post: no element outside the subarray is affected.
*/
public void sort(Comparator compare)
throws IncomparableException
{
selectionSort(0,size()-1,compare);
} // sort()
// +----------------------+------------------------------------
// | Local Helper Methods |
// +----------------------+
/**
* Sort all the elements in the subarray between lb and ub.
* Pre: 0 <= lb <= ub < size()
* Pre: the elements in the array are comparable using
* a lessEqual method.
* Post: elementAt(lb) <= elementAt(lb+1) <= ... elementAt(ub).
* Post: no element is added to or removed from the subarray.
* Post: no element outside the subarray is affected.
*/
protected void selectionSort(int lb, int ub, Comparator compare)
throws IncomparableException
{
// Variables
int index; // Index of the largest element in subrange
// Base case: one element, so it's sorted. (Don't need to check
// empty subarray because of preconditions.)
if (lb == ub) return;
// Find the index of the largest element in the subrange
index = indexOfLargest(lb,ub,compare);
// Swap that element and the last element
swap(index, ub);
// Sort the rest of the subarray (if there is any)
// Note that we don't have to compare ub-1 to lb, since
// the preconditions and the base case take care of it.
selectionSort(lb,ub-1,compare);
} // selectionSort
/**
* Find the index of the largest element in a subarray
* Pre: 0 <= lb <= ub < size()
* Pre: the elements in the vector are comparable using
* a lessEqual method
* Post: returns I s.t. for all i, lb <= i <= ub,
* elementAt(I) >= elementAt(i)
*/
protected int indexOfLargest(int lb, int ub, Comparator compare)
throws IncomparableException
{
// Variables
int guess; // Current guess as to index of largest
// Make initial guesses
guess = lb;
// Repeatedly improve our guesses until we've looked at
// all the elements
for(int i = lb+1; i <= ub; ++i) {
if (compare.precedes(get(guess),get(i))) {
guess = i;
} // if
} // for
// That's it
return guess;
} // indexOfLargest
} // SelectionSortable
import SelectionSortable;
import SimpleOutput;
import StringComparator;
/**
* A simple test of selection sort.
*
* @author Samuel A. Rebelsky
* @version 1.0 of September 1999
*/
public class TestSS {
public static void main(String[] args)
throws Exception
{
SimpleOutput out = new SimpleOutput();
SelectionSortable stuff = new SelectionSortable(args);
stuff.sort(new StringComparator());
for (int i = 0; i < stuff.size(); ++i) {
out.println(i + ": " + stuff.get(i));
} // for
} // main(String[])
} // class TestSS
Open the input file
Open a temporary file for the "more sorted" version
Let largestSoFar = the first element in the input file
While (elements remain in the input file)
Let nextElement = the next element in the input file
If nextElement < largestSoFar then
Write nextElement to the temporary file
Else
Write largestSoFar to the temporary file
Set largestSoFar to nextElement
// We've read the whole file (N elements), but only written
// N-1 elements. Write the last one.
Write largestSoFar to the temporary file
Close the input file
Close the temporary file
Replace the input file with the temporary file
Tuesday, 18 January 2000
Tuesday, 7 March 2000
Back to Introduction to Sorting. On to More Efficient Sorting Algorithms.
[Instructions] [Search] [Current] [News] [Syllabus] [Glance] [Links] [Handouts] [Project] [Outlines] [Labs] [Assignments] [Quizzes] [Exams] [Examples] [EIJ] [JPDS] [Tutorial] [API]
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS152/2000S/Outlines/outline.26.html
Source text last modified Tue Mar 7 09:50:17 2000.
This page generated on Tue Mar 7 09:54:43 2000 by Siteweaver. Validate this page's HTML.
Contact our webmaster at rebelsky@grinnell.edu