java: search for the minimum in a table 2d and restore the position of the minimum (row and coumn)

advertisements

I have a 2d array from which I need to know the minimum value. It is possible that the number is more than once inside the array, in this case the first one of them will be the minimum. Afterwards I will need to know at which position (row and column) the minimum value was found.

I already have the part where I am searching for the minimum, but I am stuck with the exact position. Below you will see my code so far.

double lowest = Double.parseDouble(excelMatrix[1][1]);

for(int r = 1; r<excelMatrix.length-1; r++){

   for(int c = 2; c<excelMatrix[r].length; c++){

      double number = Double.parseDouble(excelMatrix[r][c]);
         if(lowest > number) lowest = number;
   }
}
System.out.print(lowest);

I hope someone might be able to help me with this problem. Thank you very much in advance!


Indxing in Java is 0-based, so you are ignoring the first row completely. After that you are ignoring all the elements in the first column except excelMatrix[1][1]. The correct implementation will be:

double lowest = Double.parseDouble(excelMatrix[0][0]);
int row = 0, column = 0;

for(int r = 0; r< excelMatrix.length; r++) {
    for(int c = 0; c<excelMatrix[r].length; c++) {
        double number = Double.parseDouble(excelMatrix[r][c]);
        if(lowest > number) {
            lowest = number;
            row = r, column = c;
        }
    }
}
System.out.print(lowest + " at row: " + row + "and column: " + column);