我一整天都在研究这个问题,但是找不到下一步该做什么。我有它排序行,但它不会完全排序最后一行。这是我的代码。我知道一旦我或某人得到这个,我会感到愚蠢。谢谢你
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;
}
}
答案 0 :(得分:2)
你走在正确的轨道上,但问题是你错误地认为for(int row = 0; row < m.length ; row++)
是你的外部气泡循环。它实际上只是“加载”2-d数组中下一行的循环。所以你需要添加缺少的循环:
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] = //...
}
}
}
答案 1 :(得分:0)
最终代码产品
public class Sort2DRowTest
{
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("Sort method");
sortRow(matrix);
System.out.println();//Spacer
System.out.println("After 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();
}
}
public static int[][] sortRow(int[][] m)
{
int[][] result = new int[m.length][m[0].length];
// Copy from m to result
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
result[i][j] = m[i][j];
int temp = 0;
for(int row = 0; row < result.length ; row++)
{
for(int col = 0; col < result[row].length; col++){ //This is the real outer bubblesort loop. Change it to m[row].length
for(int nextCol = col; nextCol < result[row].length; nextCol++) {
if(result[row][col] > result[row][nextCol])
{
temp = result[row][col];
result[row][col] = result[row][nextCol];
result[row][nextCol] = temp;
}
}
System.out.print(result[row][col] + " ");
}
System.out.println();
}
//int[][] result = m;
return result;
}
}