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.
// Calls: indexOfLargest.
// ---------------------------------------------------
  // 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;
  }  // end for
}  // end selectionSort


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;  // index of largest item
}  // end indexOfLargest
