[英]two dimensional array sorting using all elements
我正在程序中处理此代码,似乎问题出在我停止第二维内循环的那一行。
这是数组的示例输出
当我运行此代码时,输出为:
我的预期输出是:
一个数字:“ 6”不在正确的位置。 这是因为当我尝试运行在for循环上方有嵌套for循环的部分时,它只运行一次,因此只检查第一列而不是到达第六列的第三列。 问题是我只在从行#0列#0到行#2列#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);
}
问题出在您搜索max元素的循环中。 假设您有数组5x5,并且x=1
和y=1
。 然后循环将仅检查以下元素:[0] [0],[0] [1],[1] [0],[1] [1]。 但它也应检查[0] [2],[0] [3],[0] [4]。
使用先前的代码,您仅检查了以下单元格:
XX...
XX...
.....
.....
.....
但是您需要检查以下内容:
XXXXX
XX...
.....
.....
.....
所以你需要这样的东西:
for(i = 0;i <= x; i++) {
int upper; // How many elements we need to check on current row.
if (i != x) {
upper = len - 1; // We are not in last row, so check all elements.
} else {
upper = y; // On the last row we need to check only elements up to y.
}
for(j = 0;j <= upper; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
}
我的代码完全检查每一行,直到最后一行。
编辑
如果您使用:
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
...
}
}
那么您只能在(0,0)中的左上角和(y,x)中的右下角膜上进行矩形迭代。 例如x = 4,y = 3:
XXX...
XXX...
XXX...
XXX...
......
但是您的目标是在最后一行完全之前完成每一行。 因此,请完全检查第0、1和2行,以及第3行中的3个元素。 我的代码做到了。 upper
显示了我们需要检查的所有行中有多少个值,除了最后一个等于len - 1
(检查完整行),我们需要检查所有行。 最后一个是y
。
您的交换代码(以int temp = twodiArray
)在主迭代循环之外。 它需要在最里面的循环内移动。
顺便说一句,您可以进行交换而无需存储索引。
就个人而言,为了避免混淆,我认为它好像是一维数组。
// I'm assuming that columnCount and rowCount are stored somewhere
public int getNthElement(int index) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
return twodiArray[rowIndex][colIndex];
}
public void setNthElement(int index, int value) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
twodiArray[rowIndex][colIndex] = value;
}
public void sortArray(int[][] array) {
int elementCount = rowCount * columnCount;
int curIndex = elementCount - 1;
while (curIndex >= 0) {
int highestIndex = -1;
int highestValue = 0;
for (int i = 0; i <= curIndex; i++) {
int nthValue = getNthElement(i);
if (nthValue > highestValue) {
highestIndex = i;
highestValue = nthValue;
}
}
int swapValue = getNthElement(curIndex);
setNthElement(curIndex, highestValue);
setNthElement(highestIndex, swapValue);
curIndex--;
}
}
您可以看到我仍然使用2D数组,并且从不使用实际的1D数组,但是此代码将其索引为数组,就好像它是 1D数组一样。 (希望这在您的教授看来是有效的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.