Reputation: 5
I'm trying to sort this 2d array in ascending order from {4,2},{1,7},{4,5},{1,2},{1,1},{4,1}
to this {1,1},{1,2},{1,7},{4,1},{4,2},{4,5}
. But for some reason it still gives me the original array and doesnt sort. What am I missing?
public class Sort {
public static void main(String[] args) {
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
sort(array);
print(array);
}
//Row Length
public static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.print("{" + m[i][j] + "}" + " ");
}
System.out.println();
}
}
public static int sort(int A[][]) {
int newArray = 0;
for (int i = 0; i < A.length; i++) {
for (int j = i + 1; j < A[i].length - 1; j++) {
if (A[j][0] > A[j + 1][0]) {
int temp = 0;
temp = A[i][j];
A[i][j] = A[i + 1][j + 1];
A[i + 1][j + 1] = A[i][j];
System.out.print(" " + A[i][j]);
}
}
}
return newArray;
}
}
Upvotes: 0
Views: 235
Reputation: 8904
This does what you want:
Your if statement never executed, because your logic was wrong when doing comparisons.
Consequently temp never ever got set in your original code.
To top that off, temp
should have been an int[]
, not an int
.
There was also no need to return an int
from the sort method.
I also slightly tweaked your print routine.
import static java.lang.System.out;
public class Playground {
public static void main(String[] args) {
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
sort(array);
print(array);
}
public static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
if (i > 0) {
out.print(",");
}
out.print("{" + m[i][0] + "," + m[i][1] + "}");
}
out.println();
}
public static void sort(int A[][]) {
boolean unsorted = true;
while (unsorted) {
unsorted = false;
for (int i = 0; i < A.length - 1; i++) {
if ((A[i][0] > A[i + 1][0])
|| ((A[i][0] == A[i + 1][0])
&& (A[i][1] > A[i + 1][1])
)) {
int[] temp = new int[2];
temp[0] = A[i][0];
temp[1] = A[i][1];
A[i][0] = A[i + 1][0];
A[i][1] = A[i + 1][1];
A[i + 1] = temp;
unsorted = true;
}
}
}
}
}
You can see it running here.
Upvotes: 1
Reputation:
You can use the comparator chaining to sort
first by one column and then by another column:
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
Arrays.sort(array, Comparator
.<int[]>comparingInt(arr -> arr[0])
.thenComparing(arr -> arr[1]));
System.out.println(Arrays.deepToString(array));
// [[1, 1], [1, 2], [1, 7], [4, 1], [4, 2], [4, 5]]
See also: Sorting a 2d array by values in more than one column
Upvotes: 0