0
我有一個二維數組,我想通過數組第二列值冒泡排序它。BubbleSort二維數組行按特定列值
我把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]]
您只能在數組上進行一次傳遞。 [Bubblesort](http://en.wikipedia.org/wiki/Bubble_sort)不是O(n),它是O(n^2)。你似乎錯過了另一個循環。查看維基百科文章中的鏈接僞代碼,並與您的代碼進行比較。 –
@JamesMontagne再次看到問題,我更新它。 – Sajad