java – 按行排序二维数组

要求是对二维数组的行进行排序.我觉得我的代码非常接近完成,但我无法弄清楚为什么它没有显示已排序的数组.我忘了提到我们不允许使用预制的排序方法.问题很可能出在sortRows方法中.无论如何,这是我的代码:

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;
 }
}

最佳答案 它看起来像这个块:

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

永远不会发生.因为你刚才将currentMin分配给m [j] [i]前面的两行.如果检查,我相信你想用k.就像是

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