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

Answer:

Yes.


Selection Sort (with Strings)

Here is selection sort with an array of String references:

// Sort an array of Strings
  public static void selectionSort( String[] array )
  {
    
    // Find the string reference 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 string reference that should go into cell j.
      // Look through the unsorted strings (those at j or higher) for the one that is first in lexicographic order
      int min = j;
      for ( int k=j+1; k < array.length; k++ )
        if ( array[k].compareTo( array[min] ) < 0 ) min = k;  

      // Swap the reference at j with the reference at min 
      String temp = array[j];
      array[j] = array[min];
      array[min] = temp;
    }
  
  }

Here (again) is selection sort for integers:

 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;
    }
  
  }

There is little difference between the methods.


QUESTION 5:

Compare this statement from integer selection sort

if ( array[k] < array[min] ) min = k;  

with this statement:

if ( array[k].compareTo( array[min] ) < 0 ) min = k;  

Are the two statements doing equivalent things?


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