我现在正在我的程序中处理这段代码,似乎问题出在我停止第二维内部循环的那一行。
这是数组的示例输出
- 9 6 6
- 7 6 4
- 4 8 5
当我运行此代码时,输出是:
- 4 4 6
- 5 6 6
- 7 8 9
我的预期输出是:
- 4 4 5
- 6 6 6
- 7 8 9
一个数字:“6”不在正确的位置。这是因为当我尝试运行在 for 循环上方有嵌套 for 循环的部分时,它只运行一次,因此它只检查第一列而不是到达 6 所在的第三列。问题是我需要限制该循环只读取从row#0 column#0到row#2 column#0的最高数字。
我该如何解决这个问题?我想过使用一维数组并将所有二维数组元素放入其中并对其进行排序,然后将其放回二维数组并再次打印,但这不会使我的代码解决对二维数组进行排序所需的过程。
public static void sortArray(){
int x = len-1, y = len-1;
int iKey=0,jKey=0;
int cnt=0;
do{
cnt++;
if(y==-1){
x--;
y=len-1;
}
System.out.println(cnt+".)"+x+"-"+y);
int hi = -1;
for(i = 0;i <= x; i++)
for(j = 0;j <= y; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
int temp = twodiArray[iKey][jKey];
twodiArray[iKey][jKey] = twodiArray[x][y];
twodiArray[x][y] = temp;
//dispArray();
y--;
}while(cnt<9);
}