java - BubbleSort 2D array rows by a specific column values -
i have two- dimensional array , want bubble sort rows array second column value.
i take arrival time
, service time
values user , want bubble sort array second column value(arrival time
).
first column process number.
static int[][] atst = new int[5][5]; (int = 0; < atst.length; i++) { system.out.print("arrival time process " + + ": "); atst[i][1] = in.nextint(); } (int = 0; < atst.length; i++) { system.out.print("enter service times process " + + ": "); atst[i][2] = in.nextint(); } system.out.println("before sorting: " + arrays.deeptostring(atst)); (int = 0; < atst.length; i++) { (int j = 1; j < (atst.length - 1); j++) { if (atst[j - 1][1] > atst[j][1]) { // 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; }
the swaprows
method works, not sort array completely.
result:
arrival time process 0: 5 arrival time process 1: 4 arrival time process 2: 3 arrival time process 3: 2 arrival time process 4: 1 enter service times process 0: 2 enter service times process 1: 3 enter service times process 2: 4 enter service times process 3: 5 enter service times 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]]
whereas result should this:
[[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]]
in updated code, bounds of inner loop incorrect:
for (int j = 1; j < (atst.length - 1); j++) {
you excluding last element subtracting 1 here, why rest of array sorted except last element. should be:
for (int j = 1; j < atst.length; j++) {
Comments
Post a Comment