[Instructions] [Search] [Current] [Syllabus] [Links] [Handouts] [Outlines] [Labs] [More Labs] [Assignments] [Quizzes] [Exams] [Examples] [Book] [Tutorial] [API]
Back to Binary Search. On to More Efficient Sorting Algorithms.
Held Thursday, October 7, 1999
Overview
Today, we'll visit the issue of sorting: turning a collection of elements into a collection in which smaller elements precede larger elements. Our focus will primarily be on sorting arrays.
Notes
Contents
Handouts
Summary
/**
* A objects of values which can be indexed by
* integers from 0 to size(). Basically, a wrapper
* class for Java's built-in arrays.
*
* @author Samuel A. Rebelsky
* @version 1.0 of September 1999
*/
public class Array {
// +--------+--------------------------------------------------
// | Fields |
// +--------+
/** The elements of the objects. */
public Object[] objects;
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new array which holds up to n elements.
* Initially, each element is null.
*/
public Array(int n) {
objects = new Object[n];
} // Array(int)
/**
* Build a new array which holds the specified
* set of elements.
*/
public Array(Object[] elements) {
objects = new Object[elements.length];
for (int i = 0; i < elements.length; ++i) {
objects[i] = elements[i];
}
} // Array(Object[])
// +-----------+-----------------------------------------------
// | Accessors |
// +-----------+
/**
* Get the ith element of the array.
*
* @exception ArrayIndexOutOfBoundsException
* For the obvious reasons.
*/
public Object get(int i) {
return objects[i];
} // get(int)
/**
* Get the number of elements in the array.
*/
public int size() {
return objects.length;
} // size()
// +-----------+-----------------------------------------------
// | Modifiers |
// +-----------+
/**
* Set the ith element of the array.
*
* @exception ArrayIndexOutOfBoundsException
* For the obvious reasons.
*/
public void set(int i, Object value) {
objects[i] = value;
} // set(int, Object)
/**
* Swap the ith and jth elements of the array.
* Included because it's commonly used during sorting.
*/
public void swap(int i, int j) {
Object temp = objects[i];
objects[i] = objects[j];
objects[j] = temp;
} // swap(int,int)
} // class Array
import Comparator;
import IncomparableException;
/**
* Things that you can tell to sort themselves.
*/
public interface Sortable {
/**
* Sort the contents of the thing using a comparator
* to compare elements.
* Pre: The elements can be compared.
* Post: The elements are sorted. Each element is no greater
* the the next element.
* Post: No elements are added or deleted.
*
* @exception IncomparableException
* if there are pairs of elements that cannot be compared.
*/
public void sort(Comparator compare)
throws IncomparableException;
} // Sortable()
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.lessThan(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[])
} // clas TestSS
import SelectionSortable;
/**
* Arrays that you can sort using iterative selection sort.
*
* @author Samuel A. Rebelsky
* @version 1.0 of October 1999
*/
public class NewSelectionSortable
extends SelectionSortable
implements Sortable
{
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new array which holds up to n elements.
* Initially, each element is null.
*/
public NewSelectionSortable(int n) {
super(n);
} // NewSelectionSortable(int)
/**
* Build a new array which holds the specified
* set of elements.
*/
public NewSelectionSortable(Object[] elements) {
super(elements);
} // NewSelectionSortable(Object[])
// +-------------------+---------------------------------------
// | Overriden Methods |
// +-------------------+
/**
* Sort all the elements in the array using iterative 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
{
// Starting at the top of the array and working your way down
// the array
for (int i = size()-1; i > 0; --i) {
// Put the largest element at the current position.
swap(indexOfLargest(0,i,compare), i);
} // for
} // sort()
} // NewSelectionSortable
import Array;
import Sortable;
/**
* Arrays that you can sort using insertion sort.
*
* @author Samuel A. Rebelsky
* @version 1.0 of October 1999
*/
public class InsertionSortable
extends Array
implements Sortable
{
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new array which holds up to n elements.
* Initially, each element is null.
*/
public InsertionSortable(int n) {
super(n);
} // InsertionSortable(int)
/**
* Build a new array which holds the specified
* set of elements.
*/
public InsertionSortable(Object[] elements) {
super(elements);
} // InsertionSortable(Object[])
// +-----------------------+-----------------------------------
// | Methods from Sortable |
// +-----------------------+
/**
* Sort the array.
*/
public void sort(Comparator compare) {
} // sort(Comparable)
/**
* Sort the array.
* Pre: the elements in the are are comparable using lessEqual.
* Post: get(lb) <= get(lb+1) <= ... <= get(ub)
* Post: elements are neither added to nor removed.
*/
protected void insertionSort(int lb, int ub, Comparator compare)
throws IncomparableException
{
// An object that we're about to insert.
Object tmp;
// The correct place for that element in the sorted subarray.
int place;
// Initially, we know that the first element is "sorted" (all
// one element lists are sorted), so we step through the elements
// starting with the second element.
for (int i = 2; i < size(); ++i) {
// Grab the element.
tmp = get(i);
// Clear out the element.
set(i,null);
// Find the place.
place = findPlace(0,i-1,compare);
// Put the element there.
insertElementAt(i,tmp);
} // for(i)
} // insertionSort(int,int)
/**
* Find the correct position for an element.
* Pre: Elements start through i are sorted
* Post: Returns an i such that elements 0 through i-1 are
* less than or equal to the element and elements i
* through end are greater than or equal to the element.
*/
protected int findPlace(int start, int end, Comparator compare)
throws IncomparableException
{
// STUB
return start;
} // findPlace(int,int,Comparator)
/**
* Insert an element at position pos, shifting the remaining
* elements to the right.
*/
protected void insertElementAt(int pos, Object element) {
// STUB
} // insertElementAt(int,Object)
} // InsertionSortable
findPlace() (which finds the proper
place in the vector to insert the element). Each insertion
requires O(n) steps, and each place determination takes
O(log_2(n)) steps (as long as we can use binary search, so the
running time is O(n*(n+log_2(n)) which is O(n^2).
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, 10 August 1999
Tuesday, 5 October 1999
Back to Binary Search. On to More Efficient Sorting Algorithms.
[Instructions] [Search] [Current] [Syllabus] [Links] [Handouts] [Outlines] [Labs] [More Labs] [Assignments] [Quizzes] [Exams] [Examples] [Book] [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/99F/Outlines/outline.25.html
Source text last modified Tue Oct 5 16:46:55 1999.
This page generated on Tue Oct 5 16:47:23 1999 by Siteweaver. Validate this page's HTML.
Contact our webmaster at rebelsky@grinnell.edu