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

Answer:

No.

Sorting the array of object references does not change the location of the actual objects.


Selection Sort with Boxes

Here is selection sort modified to sort an array of references to Box objects:

// Sort an array of Box references
  public static void selectionSort( Box[] array )
  { 
    // Find the Box reference that should go in each cell of
    // the array, from cell 0 to the end
    for ( int j=0; j < array.length-1; j++ )
    {
      // Find min: the index of the reference that should go into cell j.
      // Look through the unsorted references (those at j or higher)
      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 
      Box temp   = array[j];
      array[j]   = array[min];
      array[min] = temp;
    }
  }

The method is the same as the method to sort Strings, except that references have been changed from String to Box.

Examine how compareTo() is used:

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

This statement is deciding if the the Box pointed to by array[k] is less than the Box pointed to by array[min]. If so, min is updated. The statement is using the compareTo() method that the programmer wrote for Box. Changing that method will change the order.


QUESTION 9:

Say that an application needed Boxes in order of each Box's largest dimension. How could you do this?


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