我有一个二维数组,我想按数组第二列值对其行进行冒泡排序。
我从用户处获取到达时间
和服务时间
值,并希望按数组第二列值(到达时间
)对其进行冒泡排序。
第一列是进程号。
static int[][] atst = new int[5][5];
for (int i = 0; i < atst.length; i++) {
System.out.print("Arrival time for process " + i + ": ");
atst[i][1] = in.nextInt();
}
for (int i = 0; i < atst.length; i++) {
System.out.print("Enter service Times for process " + i + ": ");
atst[i][2] = in.nextInt();
}
System.out.println("Before sorting: " + Arrays.deepToString(atst));
for (int i = 0; i < atst.length; i++) {
for (int j = 1; j < (atst.length - 1); j++) {
if (atst[j - 1][1] > atst[j][1]) { // Then swap!
int[] tempRow = atst[j - 1];
atst[j - 1] = atst[j];
atst[j] = tempRow;
}
}
}
System.out.println("After sorting :" + Arrays.deepToString(atst));
public static void swapRows(int[][] array, int rowA, int rowB) {
int[] tempRow = array[rowA];
array[rowA] = array[rowB];
array[rowB] = tempRow;
}
swapRows
方法可以工作,但它不能完全对数组进行排序。
结果:
Arrival time for process 0: 5
Arrival time for process 1: 4
Arrival time for process 2: 3
Arrival time for process 3: 2
Arrival time for process 4: 1
Enter service Times for process 0: 2
Enter service Times for process 1: 3
Enter service Times for process 2: 4
Enter service Times for process 3: 5
Enter service Times for process 4: 2
Before sorting: [[0, 5, 2, 0, 0], [1, 4, 3, 0, 0], [2, 3, 4, 0, 0], [3, 2, 5, 0, 0], [4, 1, 2, 0, 0]]
After sorting :[[3, 2, 5, 0, 0], [2, 3, 4, 0, 0], [1, 4, 3, 0, 0], [0, 5, 2, 0, 0], [4, 1, 2, 0, 0]]
结果应该是这样的:
[[4, 1, 2, 0, 0],[3, 2, 5, 0, 0],[2, 3, 4, 0, 0],[1, 4, 3, 0, 0],[0, 5, 2, 0, 0]]
最佳答案
在更新的代码中,内部循环的边界不正确:
for (int j = 1; j < (atst.length - 1); j++) {
在这里,您通过减去 1 来排除最后一个元素,这就是为什么除了最后一个元素之外,数组的其余部分都被排序的原因。应该是:
for (int j = 1; j < atst.length; j++) {
关于java - 按特定列值对 2D 数组行进行冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22973903/