[英]Lexicographically sort an array of points
I am trying to solve an NX2 array of all integers in lexicographic order. 我正在尝试按字典顺序解决所有整数的NX2数组。 I am not getting a way how to achieve it.
我没有办法实现它。 Also, this should be done is as least time as possible.
另外,应尽可能减少时间。 Here's the example.
这是例子。
Input 输入项
2 2
1 1
4 3
2 1
10 1
Output 输出量
1 1
2 1
2 2
4 3
10 1
Point
with two fields of integers. Point
。 This is basically the same problem as sorting a bunch of integers, except that instead of integers you have a set of objects (in this case tuples - or in your code two item int arrays) that need to be sorted. 这与排序一堆整数基本上是相同的问题,不同之处在于,不是整数,而是需要排序的一组对象(在这种情况下为元组-或在代码中为两个int数组)。
Unlike Python, Java does not automatically infer a lexicographical ordering for things like int[], so you can just pass it into a sort function and expect it to work. 与Python不同,Java不会自动推断出诸如int []之类的字典顺序,因此您可以将其传递给sort函数,并期望它可以工作。 Fortunately, java allows you to define what the ordering should be and then use the built in sort method to sort it.
幸运的是,java允许您定义排序顺序,然后使用内置的sort方法对其进行排序。 This is done by implementing a
Comparator
and then defining its compare
method that tells it how to compare two objects. 这是通过实现
Comparator
,然后定义compare
方法来告诉它如何比较两个对象来完成的。
A (very simplified) example given below. 下面是一个(非常简化的)示例。
import java.util.*;
class Main{
public static void main(String args[]){
int[][] array={{2,2},{1,1},{4,3},{2,1},{10,1}};
Arrays.sort(array, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
//assumes array length is 2
int x,y;
if (a[0]!=b[0]) {
x=a[0];y=b[0];
}
else{
x=a[1];y=b[1];
}
if (x<y) return -1;
else if (x==y) return 0;
else return +1;
}
});
for(int[] term: array){
System.out.println(Arrays.toString(term));
}
}
}
Here try using this Point class with the comparator: 在这里,尝试将此Point类与比较器一起使用:
class MyPoint implements Comparable <MyPoint> {
int x, y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(MyPoint pt) {
int cmp = Integer.compare(x, pt.x);
if (cmp == 0) {
return Integer.compare(y, pt.y);
} else {
return cmp;
}
}
}
After all you need to do is create a some Point objects and sort them. 毕竟,您需要做的是创建一些Point对象并对其进行排序。 Here's an example:
这是一个例子:
ArrayList<MyPoint> pts = new ArrayList<MyPoint>(4);
pts.add( new MyPoint(3, 5));
pts.add( new MyPoint(2, 3));
pts.add( new MyPoint(3, 4));
pts.add( new MyPoint(1, 5));
Collections.sort(pts);
for (int i = 0; i < pts.size(); i++) {
MyPoint pt = pts.get(i);
System.out.println(pt.x + " " + pt.y);
}
Output: 输出:
1 5
2 3
3 4
3 5
@amit explained what to do. @amit解释了该怎么做。 I just wanted to add that you do not want to sort numeric data lexicographically.
我只是想补充一点,您不想按字典顺序对数字数据进行排序。 If you do this you get
如果你这样做,你会得到
1 1
10 1
2 1
etc.
Because lexicographically 10 is just after 1 and before 2. You want to perform regular numeric sort. 因为按字典顺序10在1之前和2之后。您想要执行常规数字排序。 Sometimes it is called "natural" sort.
有时将其称为“自然”排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.