Sort a two-dimensional array by row

The requirement is to sort the rows of a two-dimensional array. I feel that my code is very close to execution, but I cannot understand why it does not display a sorted array. I forgot to mention that we are not allowed to use preprocessing methods. The problem is most likely in the sortRows method. Anyway, here is my code:

public class RowSorting
{
   public static void main(String[] args) 
{
  double[][] numbers  = new double[3][3];
  double[][] number  = new double[3][3];
  int run = 0;
  String answer = "";

  while (run == 0)
     {
       Scanner input = new Scanner(System.in);
       System.out.print("Enter a 3-by-3 matrix row by row: ");
       for(int row = 0; row < numbers.length; row++)
        {
         for(int column = 0; column < numbers[row].length; column++)
          {
           numbers[row][column] = input.nextDouble();
          }
        }
       for(int row = 0; row < numbers.length; row++)
        {
         for(int column = 0; column < numbers[row].length; column++)
          {
           System.out.print(numbers[row][column] + " ");
          }
         System.out.print("\n");
        } 
       System.out.println("The sorted array is: \n");
       number = sortRows(numbers);
       for(int row = 0; row < number.length; row++)
        {
         for(int column = 0; column < number[row].length; column++)
          {
           System.out.print(number[row][column] + " ");
          }
         System.out.print("\n");
        } 




   System.out.print("\nWould you like to continue the program (y for yes or    anything else exits): ");
       answer = input.next();

       if(answer.equals("y"))
        {
         continue;
        }
       else
         break;
      }




}
 public static double[][] sortRows(double[][] m)
{
  for(int j = 0; j < m[j].length - 1; j++)
   {
    for(int i = 0; i < m.length; i++)
    {
      double currentMin = m[j][i];
      int currentMinIndex = i;

      for(int k = i + 1; k < m[j].length; k++)
      {
       if(currentMin > m[j][i])
       {
        currentMin = m[j][i];
        currentMinIndex = k;
       }
      }
    if(currentMinIndex != i)
    {
     m[currentMinIndex][j] = m[j][i];
     m[j][i] = currentMin;
    }
    }
   }
  return m;
 }
}
+4
source share
2 answers

It looks like this block:

if(currentMin > m[j][i])
   {
    currentMin = m[j][i];
    currentMinIndex = k;
   }

Will never happen. Since you just assigned currentMin m [j] [i] to the two lines in front of it. I believe that you want to use k in this case when checking. Sort of

if (currentMin > m[j][k]){
    currentMin = m[j][k];
    currentMinIndex = k;
}
+1
source

,

if(currentMin > m[j][i]) ...

m[currentMinIndex][j] = m[j][i];

.

for(int j = 0; j < m[j].length - 1; j++) ...
    for(int i = 0; i < m.length; i++) ...

. , for-loops, . . j-index for-loop, .

0

Source: https://habr.com/ru/post/1614910/


All Articles