基于列值对矩阵进行排序的最佳Java方法

huangapple go评论78阅读模式
英文:

Best method to sort a matrix in java based on column values

问题

我正在尝试根据列中的值对矩阵进行排序。是否有内置的方法可以实现这一点,就像 Arrays.sort(),或者即使我将其转换为列表然后使用 Collections.sort() 也可以。

如果没有,那么最佳的实现排序函数的方法是什么?(我将"最佳"定义为不需要太长时间来实现,但运行时也不会很慢)。

例如,如果我有:

int[][] matrix:

[0, 30]
[5, 10]
[15, 20]

我想要将它排序为(列的值已排序):

[5, 10]
[15, 20]
[0, 30]

另一个例子:

int[][] matrix:

[7, 10]
[2, 4]

我想要将它排序为(列的值已排序):

[2, 4]
[7, 10]
英文:

I'm trying to sort a matrix based on the values in the column. Is there any in-built way to do this, like Arrays.sort() or even if I turned it into a List and then did Collections.sort().

If not, what is the best way to implement the sort function myself? (I would define best as something that doesn't take too long to implement but also doesn't have a very slow runtime).

For example, if I have:

int[][] matrix:

[0, 30]
[5, 10]
[15, 20]

I want to sort it to (the column values were sorted): 

[5, 10]
[15, 20]
[0, 30]

Another example:

int[][] matrix:

[7,10]
[2,4]

I want to sort it to (the column values were sorted):

[2,4]
[7,10]


</details>


# 答案1
**得分**: 2

只需执行:

```java
Arrays.sort(matrix, Comparator.comparingInt(row -> row[1]));

这将按照每行的第二列进行排序,并假设每行至少有两列。

它使用 Arrays.sortComparator.comparingInt 来提取每行的第二个元素。

英文:

Just do:

Arrays.sort(matrix, Comparator.comparingInt(row -&gt; row[1]));

This sorts rows by its 2nd column and assumes each row has at least 2 columns.

It uses Arrays.sort and Comparator.comparingInt to extract the 2nd component of each row.

答案2

得分: 0

Arrays.sort(matrix, Comparator.comparingInt(row -> row[1]));

其中1 表示要按列排序

它使用 `Arrays.sort` 对外部数组包含数据数组进行排序在这些行中位置 [1] 处的值进行比较以正确排序它们您还可以按任何其他列或行长度进行比较例如

Arrays.sort(matrix, Comparator.comparingInt(row -> row.length));
英文:
Arrays.sort(matrix, Comparator.comparingInt(row -&gt; row[1]));

where 1 is column to sort by.

It sorts your outer array (which contains arrays of data) with Arrays.sort. Values at a position 1 are compared in these rows to sort them properly. You can also compare by any other column, or row length, etc, like that:

 Arrays.sort(matrix, Comparator.comparingInt(row -&gt; row.length));

huangapple
  • 本文由 发表于 2020年10月20日 00:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64431766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定