Annie T
Annie T

Reputation: 37

Switching the smallest and largest value in an object array in Java

I'm instructed to swap the largest and smallest value in an object array in Java. I wrote my code and it seems reasonable, but for some reason the values aren't switching??? I'm not quite sure what's wrong with my code, can someone point me in the right direction? Thank you!!

This is my code:

public class Measurables
{
   /**
      Swaps the values with the smallest and largest measure.
      @param objects an array of objects of a class that implements the
      Measurable interface.
   */
   public static void swapMinAndMax(Measurable[] objects)
   {

      Measurable largest = objects[0]; 
      Measurable smallest = largest;
      for (int i = 1 ; i < objects.length ; i++)
      {
         Measurable current = objects[i];
         if ( largest.getMeasure() < current.getMeasure())
         {
            largest = current;
         }
         if (smallest.getMeasure() < current.getMeasure())
         {
            smallest = current;
         }
         Measurable temp = largest; 
         largest = smallest;
         smallest = temp;

         }
      }
}

This is what I get when I run the tester:

Testers

Running Tester.java

fail
[Uruguay, Thailand, Belgium]
Expected: [Uruguay, Belgium, Thailand]
Running Tester2.java

fail
[BankAccount[balance=1000.0], BankAccount[balance=3000.0], BankAccount[balance=2000.0]]
Expected: [BankAccount[balance=3000.0], BankAccount[balance=1000.0], BankAccount[balance=2000.0]]
Running Tester3.java

pass
[Uruguay]
Expected: [Uruguay]

Upvotes: 0

Views: 1943

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201409

You should store the indices of your elements so you can perform the swap after you determine the smallest and largest indices. Also, you seem to have swapped the comparison for smallest. Something like,

public static void swapMinAndMax(Measurable[] objects) {
    int largest = 0, smallest = 0;
    for (int i = 1; i < objects.length; i++) {
        Measurable current = objects[i];
        if (objects[largest].getMeasure() < current.getMeasure()) {
            largest = i;
        }
        if (objects[smallest].getMeasure() > current.getMeasure()) {
            smallest = i;
        }
    }
    // Now swap, we know the indexes.
    Measurable temp = objects[largest];
    objects[largest] = objects[smallest];
    objects[smallest] = temp;
}

Upvotes: 1

Related Questions