按行对二维数组进行排序

4

要求对二维数组的行进行排序。我感觉我的代码已经很接近完成了,但是我无法弄清楚为什么它没有显示出排序后的数组。我忘记提到我们不允许使用预先制作的排序方法。问题很可能出在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;
 }
}
2个回答

1
看起来像这个块:

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

永远不会发生。因为你在两行前刚刚将currentMin分配给了m[j][i]。我认为你想在if检查中使用k。像这样:
if (currentMin > m[j][k]){
    currentMin = m[j][k];
    currentMinIndex = k;
}

1
哦,是的!非常感谢。这解决了我问题的一部分,但我还是能够尝试一下来弄清楚它。我还不得不交换currentMinIndex变量和j的值。非常感谢!!! - Austin P

0
根据ergonaut的引用,您的代码块存在问题。
if(currentMin > m[j][i]) ...

还有

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

然而,你的for循环也存在问题。

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

这两个循环结构都有些奇怪。你可能想要交换这些for循环,这样就不会抛出索引异常了。这也会让你在代码中更好地处理索引。并且修改你的j索引for循环以包含整个范围。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接