按行排序二维数组

时间:2015-11-08 02:29:34

标签: java arrays sorting

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

答案 0 :(得分:1)

看起来像这个块:

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

答案 1 :(得分: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-index for-loop以包含整个范围。