[英]Sort array by length of sub arrays
So I have a 2D array graph
that represents an adjacency list: 所以我有一个二维数graph
,它表示一个邻接表:
0:2 1 0
1:0
2:
In array format thats: 在多数民众赞成在阵列格式:
[[2,1,0],[0],[]]
What I want to do is sort a specific row (say graph[0]
) by the length of the sub array (the edge list). 我想要做的是根据子数组(边缘列表)的长度对特定的行 (例如graph[0]
)进行排序。
In the example above the sorted graph
would look like: 在上面的示例中,排序后的graph
如下所示:
0:0 1 2
1:0
2:
[[0,1,2],[0],[]]
Since graph[0].length = 3
and graph[1].length = 1
and graph[2].length = 0
. 由于graph[0].length = 3
和graph[1].length = 1
且graph[2].length = 0
。
I've tried using: 我试过使用:
Arrays.sort(graph[v], new DegreeComparator(graph));
class DegreeComparator implements Comparator<Integer> {
int[][] graph;
public DegreeComparator(int[][] g) {
graph = g;
}
public int compare(Integer c1, Integer c2) {
return Integer.compare(graph[c1].length, graph[c2].length);
}
}
But the sort method won't accept this format. 但是sort方法不会接受这种格式。 Can someone explain what I'm doing wrong? 有人可以解释我在做什么错吗?
Edit for clarity: 为清楚起见进行编辑:
Because the above example uses numbers it's a bit confusing so I'll add a second case: 因为上面的示例使用数字,所以有些混乱,因此我将添加第二种情况:
0: 4 1 2
1: 1 2 3
2:
3: 4 1
4: 0
[[4,1,2],[1,2,3],[],[4,1],[0]]
Would become (if all rows were sorted): 将变为(如果所有行都已排序):
0: 1 4 2 // Row 1 has more numbers than row for which has more than row 2
1: 1 3 2
2:
3: 1 4
4: 0
[[1,4,2],[1,3,2],[],[1,4],[0]]
However, I only need to sort one row at a time! 但是,我只需要一次对一行进行排序! Not the whole thing. 不是全部。
You ask your int[] to be sorted with a Comparator 您要求将int []与比较器进行排序
Change the type of graph to Integer[][] 将图的类型更改为Integer [] []
class DegreeComparator implements Comparator<Integer> {
Integer[][] graph;
public DegreeComparator(Integer[][] g) {
graph = g;
}
public int compare(Integer c1, Integer c2) {
return graph[c2].length - graph[c1].length;
}
}
First of all just to clarify your question: you have an array of arrays called graph
. 首先只是为了澄清您的问题:您有一个称为graph
的数组数组。 You also have an array of ints (let's call it pointers
) which refers to the elements of graph
. 您还拥有一个引用了graph
元素的int数组(我们称其为pointers
)。 The fact that pointers
happens to be one of the elements of graph
isn't actually important. pointers
恰好是graph
的元素之一这一事实实际上并不重要。
Integer[][] graph = new Integer[4][];
Integer[] pointers = new Integer[] { 2, 1, 0, 3 };
graph[0] = pointers;
graph[1] = new Integer[] { 0 };
graph[2] = new Integer[] {};
graph[3] = new Integer[] { 1, 2 };
System.out.println(Arrays.toString(pointers));
// [2, 1, 0, 3]
final int[] lengths = new int[graph.length];
for (int i = 0; i < graph.length; i++) {
lengths[i] = graph[i].length;
}
Arrays.sort(pointers, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(lengths[o2], lengths[o1]);
}
});
System.out.println(Arrays.toString(pointers));
// [0, 3, 1, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.