在Java中切换对象数组中的最小值和最大值

时间:2017-08-02 00:44:22

标签: java arrays object

我被指示在Java中交换对象数组中的最大值和最小值。我写了我的代码,这似乎是合理的,但由于某种原因,值不会切换???我不太确定我的代码有什么问题,有人能指出我正确的方向吗?谢谢!!

这是我的代码:

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;

         }
      }
}

这是我运行测试人员时得到的结果:

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]

1 个答案:

答案 0 :(得分:1)

您应该存储元素的索引,以便在之后执行交换,以确定最小和最大的索引。此外,您似乎已将比较换成最小的。像,

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