Isabel Alphonse Isabel Alphonse - 2 months ago 10
Java Question

How can I print the values of a 2D array in descending order?

So I have a 2D matrix and I'm trying to print out the values from largest to smallest. I basically do this by always looking for a max and when I find it I set that position equal to

1
in
adjacencyMatrix
so that we don't count it again. Problem is when I tested the code it started out correctly by printing out the largest and then skipped the second largest. Then found the 3rd and 4th largest. Skipped some more and then finally just started printing out 0s.

Here is my code:

public static void findLongestPath(int rows, int columns, int[][] elevationMatrix, int[][] adjacencyMatrix)
{
int max = 0;

for (int x = 0; x < rows * columns; x++)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (elevationMatrix[i][j] > max && adjacencyMatrix[i][j] == 0)
{
max = elevationMatrix[i][j];
adjacencyMatrix[i][j] = 1;
}
}
}

System.out.println(max);
max = 0;
}
}


I have been staring at it for a while and can't find the bug so I though another pair of eyes might help.

P.S. Please, please, please don't tell me to sort the array because I can'd do that. I need to maintain the order of the original array.

Answer
public static void findLongestPath(int rows, int columns, int[][] elevationMatrix, int[][] adjacencyMatrix)
    {
        int max = 0;
        int cX, cY;

        for (int x = 0; x < rows * columns; x++)
        {   
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    if (elevationMatrix[i][j] > max && adjacencyMatrix[i][j] == 0)
                    {
                        max = elevationMatrix[i][j]; // possible max
                        cX = i; // store i
                        cY = j; // store j
                    }
                }
            }

            System.out.println(max); // global max
            max = 0;
            // cX and cJ now point to coordinates of global max
            // all the possible max value coordinates are ignored.
            adjacencyMatrix[cX][cJ] = 1;
        }
    }

I think you need to set adjacencyMatrix[][] = 1, after you find largest number throughout the matrix(global max), rather than finding a max(possible max).

There can be more efficient ways to do this, I'm pointing out at what needs to be done in this method to work.