gpt4 book ai didi

java - 实现以下方法对二维数组中的行进行排序

转载 作者:行者123 更新时间:2023-11-30 04:12:49 25 4
gpt4 key购买 nike

我一整天都在研究这个问题,但不知道下一步该做什么。我让它对行进行排序,但它不会完全对最后一行进行排序。这是我的代码。我知道一旦我或某人得到这个我会觉得很愚蠢。谢谢

    public class Sort2DRow
{
public static void main (String [] args)
{
int[][] matrix = {{3,5,6}, {4,1,2},{9,8,7}};

System.out.println("Before the sort");
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col <matrix[row].length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}

System.out.println();//Spacer
System.out.println("After sort method");
sortRow(matrix);

}

public static int[][] sortRow(int[][] m)
{
int temp = 0;
for(int row = 0; row < m.length ; row++)
{
for(int col = 0; col < m.length -1; col++){
if(m[row][col] > m[row][col + 1])
{
temp = m[row][col];
m[row][col] = m[row][col + 1];
m[row][col + 1] = temp;
}
}
}

for(int row = 0; row <m.length; row++){
for(int col = 0; col <m[row].length; col++){
System.out.print(m[row][col] + " ");
}
System.out.println();
}

int[][] result = m;
return result;
}

}

最佳答案

您的思路是正确的,但问题是您错误地认为 for(int row = 0; row < m.length ; row++)是你的外部冒泡排序循环。它实际上只是“加载”二维数组中下一行的循环。因此,您需要添加缺少的循环:

for(int col = 0; col < m[row].length; col++){ //This is the real outer bubblesort loop. Change it to m[row].length
for(int nextCol = col; nextCol < m[row].length; nextCol++) {
if(m[row][col] > m[row][nextCol])
{
temp = //I'll let you figure this out
m[row][col] = //....
m[row][nextCol] = //...
}
}
}

关于java - 实现以下方法对二维数组中的行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213653/

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