英文:
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.sort
和 Comparator.comparingInt
来提取每行的第二个元素。
英文:
Just do:
Arrays.sort(matrix, Comparator.comparingInt(row -> 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 -> 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 -> row.length));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论