gpt4 book ai didi

java - 按行对二维数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 03:35:23 24 4
gpt4 key购买 nike

需求是对一个二维数组的行进行排序。我觉得我的代码快要完成了,但我不明白为什么它不显示排序后的数组。我忘了提到我们不允许使用预制的排序方法。问题很可能出在 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;
}
}

最佳答案

它看起来像这个 block :

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

永远不会发生。因为你刚刚将 currentMin 分配给了 m[j][i] 两行之前。我相信你想在 if check 中使用 k 。有点像

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

关于java - 按行对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33590097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com