import java.util.Arrays; public class Three { public static void main(String[] args) { int num[][] = { {5, 4, 45, 12}, {7, 5, 8, 85}, }; Arrays.sort(num); for(int row = 0; row<2; row++){ for(int col = 0; col<4; col++){ System.out.print(num[row][col]); } } } } 

Gives an error message. The one-dimensional array was thus sorted, what is wrong?

  • Uh ... And how do you want to sort the two-dimensional array? What should be the result? - VladD
  • Sort Ascending. From smaller value to bigger. In this case, something like 4, 5, 5, 7 ... - Alexander
  • And to repack the array? - VladD
  • Yes, (there are just symbols in order for the comment to skip ...) - Alexander

2 answers 2

You will have to manually repack the array into “flat”.

For example:

 import java.util.Arrays; class Three { public static void main(String[] args) { int num[][] = { {5, 4, 45, 12}, {7, 5, 8, 85} }; int[] flat = new int[2 * 4]; int ctr = 0; for (int row = 0; row < 2; row++) { for (int col = 0; col < 4; col++) { flat[ctr++] = num[row][col]; } } Arrays.sort(flat); ctr = 0; for (int row = 0; row < 2; row++) { for (int col = 0; col < 4; col++) { num[row][col] = flat[ctr++]; } } for (int row = 0; row < 2; row++) { for (int col = 0; col < 4; col++) { System.out.print(num[row][col] + " "); } System.out.println(); } } } 

Check: http://ideone.com/50oR4z

  • @ Alex78191: Hmm, and then how to sort? I will not think something. Will write your option? - VladD

And I would add here a little bit of streams

 import java.util.Arrays; import java.util.stream.Stream; public class Three { public static void main(String[] args) { int num[][] = { {5, 4, 45, 12}, {7, 5, 8, 85}, }; int[] numTemp = Stream.of(num).flatMapToInt(Arrays::stream).sorted().toArray(); for (int row = 0; row < 2; row++) { for (int col = 0; col < 4; col++) { num[row][col] = numTemp[row * 4 + col]; } } for (int row = 0; row < 2; row++) { for (int col = 0; col < 4; col++) { System.out.print(num[row][col] + " "); } System.out.println(); } } }