从数组java中从最大到最小排序

时间:2014-05-14 02:09:04

标签: java arrays sorting

我需要帮助排序这个数组。这是代码,它根本不排序它只是保持数组的输入方式。我已经被困在这一天了一天,无法解决任何问题。帮助将不胜感激。这是我的代码:

// sortGrossPay takes an array and sorts it by descending order

public static void sortGrossPay(String[] employeeNames, double[][] employeeInformation,
                                int numberEmployees, int GROSS_PAY)
{
int numberOfColumns = employeeInformation[HOURS].length;
 double[] oneRow = new double[numberOfColumns];

 int maxIndex;
 String strTemp;

  for(int i = 0; i < numberEmployees - 1; i++) {

  maxIndex = i;
  double maxGross = employeeInformation[i][GROSS_PAY];

  // Compare value of current maxIndex with the next number, if the next number is 
  // greater than the maxIndex, set its index as the new max

  for(int j = i + 1; j < numberEmployees; j++) {

     if (employeeInformation[i][GROSS_PAY] > employeeInformation[maxIndex][GROSS_PAY]) {

        maxIndex = j;
        maxGross = employeeInformation[i][GROSS_PAY];
     }
  } // End nested for loop

  // Replace name at current minimum index with the name found at i

  strTemp = employeeNames[maxIndex] = employeeNames[i];
  employeeNames[maxIndex] = employeeNames[i];
  employeeNames[i] = strTemp;

  oneRow = employeeInformation[maxIndex];
  employeeInformation[maxIndex] = employeeInformation[i];
  employeeInformation[i] = oneRow;

  } // End for loop
 } // End method

1 个答案:

答案 0 :(得分:0)

我认为你的第一个问题来自这项任务:

strTemp = employeeNames[maxIndex] = employeeNames[i];

尝试将该行代码更改为:

strTemp = employeeNames[maxIndex];

您正在执行的任务将employeeNames [i]的值分配给employeeNames [maxIndex]和strTemp。您需要strTemp来包含employeeNames [maxIndex]中的值,但是在您有机会存储它之前会被覆盖。 这就是为什么你的数组根本没有变化的原因。

其次,嵌套for循环中的检查应如下所示:

if (employeeInformation[j][GROSS_PAY] > employeeInformation[maxIndex][GROSS_PAY])

并且if语句中的行应如下所示:

    maxGross = employeeInformation[j][GROSS_PAY];

注意j(您正在检查索引i)。