Source of ArraySorter.java


  1: //ArraySorter.java
  2: 
  3: /**
  4:  * Class for sorting an array of base type int from smallest to largest.
  5:  */
  6: public class ArraySorter
  7: {
  8:     /**
  9:      * Precondition: Every element in anArray has a value.
 10:      * Action: Sorts the array into ascending order.
 11:      */
 12:     public static void selectionSort
 13:     (
 14:         int[] anArray
 15:     )
 16:     {
 17:         for (int index = 0; index < anArray.length - 1; index++)
 18:         {   // Place the correct value in anArray[index]
 19:             int indexOfNextSmallest = getIndexOfSmallest(index, anArray);
 20:             interchange(index, indexOfNextSmallest, anArray);
 21:             //Assertion:anArray[0] <= anArray[1] <=...<= anArray[index]
 22:             //and these are the smallest of the original array elements.
 23:             //The remaining positions contain the rest of the original
 24:             //array elements.
 25:         }
 26:     }
 27: 
 28:     /**
 29:      * Returns the index of the smallest value in the portion of 
 30:      * array that begins at the element whose index is startIndex
 31:      * ends at the last element.
 32:      */
 33:     private static int getIndexOfSmallest
 34:     (
 35:         int startIndex,
 36:         int[] a
 37:     )
 38:     {
 39:         int min = a[startIndex];
 40:         int indexOfMin = startIndex;
 41:         for (int index = startIndex + 1; index < a.length; index++)
 42:         {
 43:             if (a[index] < min)
 44:             {
 45:                 min = a[index];
 46:                 indexOfMin = index;
 47:                 // Assertion: min is smallest of a[startIndex] through a[index]
 48:             }
 49:         }
 50:         return indexOfMin;
 51:     }
 52: 
 53:     /**
 54:      * Precondition: i and j are valid indices for the array a.
 55:      * Postcondition: Values of a[i] and a[j] have been interchanged.
 56:      */
 57:     private static void interchange
 58:     (
 59:         int i,
 60:         int j,
 61:         int[] a
 62:     )
 63:     {
 64:         int temp = a[i];
 65:         a[i] = a[j];
 66:         a[j] = temp; //original value of a[i]
 67:     }
 68: }