Hello. I have a small problem, I can not sort a two-dimensional array. I just started learning java .

Can you please tell me how to do the sorting correctly?

 int[][] arrayD ={{2,3,1,5,4},{6,8,7,10,9}}; for (int i = 0; i < arrayD.length; i++) { for (int j = 0; j < arrayD.length; j++) { } } Arrays.sort(arrayD); for (int i = 0; i < arrayD.length; i++) { for (int j = 0; j < arrayD.length; j++) { } } for (int[] is : arrayD) { System.out.println(is + " "); } 
  • What sort of sorting do you need to do? Judging by the numbers, I assume that you need to sort the array either in ascending or descending order? - Egor Trutnev
  • Yes, ascending) - Roman Sychok
  • If you have not reached the comporers yet, then you can use the following solution: ru.stackoverflow.com/questions/618038/… - SlandShow

1 answer 1

Use this:

 Arrays.sort(arrayD, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o2[1], o1[1]); } }); 

Java 8 is easier to do:

 Arrays.sort(arrayD, Comparator.comparingInt(arr -> arr[1])); 

Where arr[1] is the column by which sorting will occur.

  • Переопределяем ? MB, more correctly we используем вторую версию метода sort ? - Flippy
  • @Flippy was wrong, corrected, thank you. - phen0menon