Procedure to sort a two dimensional int array depending on column
Use java.util.Arrays.sort
with a custom Comparator
.
int[][] temp = { { 1, 50, 5 }, { 2, 30, 8 }, { 3, 90, 6 },
{ 4, 20, 7 }, { 5, 80, 9 }, };
Arrays.sort(temp, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
As shmosel mentioned below, with Java 8, you can use:
Arrays.sort(temp, Comparator.comparingInt(arr -> arr[1]));
You can do this instead of writing your own sorting algorithm:
int[][] n = new int[10][];
//init your array here
List<int[]> ints = Arrays.asList(n);
Collections.sort(ints, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1]; // compare via second column
}
});
and if you want make it array again:
int[][] result = ints.toArray(n);