go to previous page   go to home page   go to next page

Why does J stop at length-2 ?

Answer:

The last index in an array is length-1 . Once the integers at indexes 0 to length-2 are sorted, the last integer at length-1 is automatically where it belongs.


Selection Sort Tester

public class SelectionSortTester
{
 
  // Sort the Array
  //
  public static void selectionSort( int[] array )
  {
    
    // Find the integer that should go in each cell j of
    // the array, from cell 0 to the end
    for ( int j=0; j<array.length-1; j++ )
    {
      // Find min: the index of the integer that should go into cell j.
      // Look through the unsorted integers (those at j or higher)
      int min = j;
      for ( int k=j+1; k<array.length; k++ )
        if ( array[k] < array[min] ) min = k;  

      // Swap the int at j with the int at min 
      int temp = array[j];
      array[j] = array[min];
      array[min] = temp;
    }
  
  }
  
  public static void main ( String[] args )
  {
    int[] values = { 17, 5, 21, 8, 19, 2, 23, 15, 4, 13 };
    
    // print out the array
    System.out.println("initial values: "); 
    for ( int val : values )
      System.out.print( val + ", " ); 
     
    // sort the array
    selectionSort( values );
  
    // print out the array
    System.out.println("\n\nsorted values: "); 
    for ( int val : values )
      System.out.print( val + ", " ); 
    System.out.println( );
 
   }
}

Here is a complete program that implements selection sort and includes a main() method for testing it. Copy and paste it to a file InSortTester.java Play with it. Change the values in the array. The programming exercises in this chapter suggest making the array much bigger and initializing it with random integers.


QUESTION 10:

Here is a proposed replacement for the "swap" portion of the sorting method:

      // Swap the int at j with the int at min 
      array[j] = array[min];
      array[min] = array[j];

Is this replacement going to work?


go to previous page   go to home page   go to next page