Question

I need help sorting this array. Here's the code, it doesn't sort at all it just keeps the array the way it was entered. I've been stuck on this for a day now and can't figure anything out. Help would be appreciated. Here's the code I have:

// 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
Was it helpful?

Solution

I think your first problem is coming from this assignment:

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

try changing that line of code to this:

strTemp = employeeNames[maxIndex];

The assignment you're doing assigns the value of employeeNames[i] to both employeeNames[maxIndex] and strTemp. You need strTemp to contain the value at employeeNames[maxIndex], but that's being overwritten before you have a chance to store it. That is why your array isn't changing at all.

Secondly, the check in your nested for loop should look like this:

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

and the line inside of the if statement should look like this:

    maxGross = employeeInformation[j][GROSS_PAY];

note the j (you're checking index i).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top