这是我的 FCFS
算法。
我有一个名为atst
的二维数组,意思是到达时间,服务时间
。
数组大小为5*5
。
我的数组的逻辑图是这样的:
第一列:进程名称
第二栏:到达时间
第三栏:服务时间(突发时间)
按到达时间(第二列)排序数组后,第四列和第五列将初始化等待时间和总时间。
我的问题是按第二列(到达时间)按升序对数组进行排序。
我的代码:
// Sort array by arrival times
int[] temp = new int[3];
for (int i = 0; i < atst.length; i++) {
if (atst[i][1] > atst[i + 1][1]) { // Then swap!
temp[i] = atst[i][1];
atst[i][1] = atst[i + 1][1];
atst[i + 1][1] = temp[i];
}
}
我使用 temp[3]
因为在排序之前其他列(第四和第五)都是空的(零)。
但是这段代码在这一行中产生了arrayOutOfBoundException
:temp[i] = atst[i][1];
。
如何解决这个问题?
最佳答案
给你:
// Sort array by arrival times
int[] temp = new int[atst.length]; //to avoid any out of bound.
for (int i = 0; i < atst.length-1; i++) { //-1 will solve
if (atst[i][1] > atst[i + 1][1]) { // Then swap!
temp[i] = atst[i][1];
atst[i][1] = atst[i + 1][1];
atst[i + 1][1] = temp[i];
}
}
希望这会起作用。对于 i
的最后一个值,您已经超出了 atst[i+1]
中的数组界限。这个-1
将解决您的arrayOutOfBoundException
问题。
编辑:试试这个:
// Sort array by arrival times
int[] temp = new int[atst.length]; //to avoid any out of bound.
for (int i = 0; i < atst.length-1; i++) { //-1 will solve
for (int j = 0; i < 2; j++) {
if (atst[i][j] > atst[i + 1][j]) { // Then swap!
temp[i] = atst[i][j];
atst[i][j] = atst[i + 1][j];
atst[i + 1][j] = temp[i];
}
}
}
关于java - 交换二维数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22966195/