我有一个二维数组,我想通过数组第二列值对它进行冒泡排序。
我从用户那里获取Arrival time
和Service time
值,并希望按数组第二列值(Arrival time
)对其进行冒泡排序。
第一列是流程编号。
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]]
答案 0 :(得分:1)
在更新的代码中,内部循环的边界不正确:
for (int j = 1; j < (atst.length - 1); j++) {
你通过在这里减去1来排除你的最后一个元素,这就是除了最后一个元素之外数组的其余部分被排序的原因。应该是:
for (int j = 1; j < atst.length; j++) {