




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Howe; Class: Algorithms and Data Structures; Subject: Computer Science; University: Colorado State University; Term: Fall 2008;
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





n
n
n " 1
n
public static void selectionSort(Comparable[] theArray, int n) { // Sorts the items in an array into ascending order. // Precondition: theArray is an array of n items. // Postcondition: theArray is sorted into ascending order. // last = index of the last item in the subarray of items yet to be sorted // largest = index of the largest item found for (int last = n-1; last >= 1 ; last--) { // Invariant: theArray[last+1..n-1] is sorted and > theArray[0..last] // select largest item in theArray[0..last] int largest = indexOfLargest(theArray, last+1); // swap largest item theArray[largest] with theArray[last] Comparable temp = theArray[largest]; theArray[largest] = theArray[last]; theArray[last] = temp; }}
private static int indexOfLargest(Comparable[] theArray, int size) { // Finds the largest item in an array. // Precondition: theArray is an array of size items; size >= 1. // Postcondition: Returns the index of the largest item in the array. int indexSoFar = 0 ; // index of largest item found so far // Invariant: theArray[indexSoFar]>=theArray[0..currIndex-1] for (int currIndex = 1 ; currIndex < size; ++currIndex) { if (theArray[currIndex].compareTo(theArray[indexSoFar])> 0 ) { indexSoFar = currIndex; } // end if } // end for return indexSoFar;}