How to sort two dimensional array lexicographically?

℡╲_俬逩灬. 提交于 2021-01-23 06:58:38

问题


Assuming we have a two-dimensional array as follows:

int[][] source = {
  {   3,  5,  6,  1},
  {   3,  3,  5, -6},
  {  -1, -3, -5, -6},
  { 124, 43, 55, -66}
};

how do we sort the multidimensional array source lexicographically?

So, as a result, I'd expect it to be:

[ [ -1, -3, -5,  -6], 
  [  3,  3,  5,  -6], 
  [  3,  5,  6,   1], 
  [124, 43, 55, -66] ]

a lot of questions on this site seem to only suggest sorting by the first element of each array or second, third etc. but not taking in consideration the entire array.


回答1:


As of JDK9, there's a new method called Arrays.compare which allows you to compare two given arrays lexicographically.

Short description of Arrays.compare from the documentation:

If the two arrays share a common prefix then the lexicographic comparison is the result of comparing two elements, as if by Integer.compare(int, int), at an index within the respective arrays that is the prefix length. Otherwise, one array is a proper prefix of the other and, lexicographic comparison is the result of comparing the two array lengths.

Given you want to modify the source array then using Arrays.sort should suffice:

Arrays.sort(source, Arrays::compare); 

Given you want a new array as a result then I'd go the stream way:

int[][] sorted = Arrays.stream(source)
                       .sorted(Arrays::compare)
                       .toArray(int[][]::new);


来源:https://stackoverflow.com/questions/53899289/how-to-sort-two-dimensional-array-lexicographically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!