Algorithm

[Algorithm] 좌표 정렬 - compareTo

로넌 2023. 1. 18. 13:02

좌표정렬 관련 문제를 만났을 때 사용가능한 알고리즘을 정리해두고자 한다.

 

class Point implements Comparable<Point> {
    public int x, y;
    Point(int x, int y){
    	this.x = x;
        this.y = y;
    }
    @Override
    public int compareTo(Point o){
    	if(this.x == o.x) return this.y - o.y;
        else return this.x - o.x;
    }
}

class Main{
	public static void main(String[] args){
    	Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Point> arr = new ArrayList<>();
        for(int i =0; i<n; i++){
        	int x = sc.nextInt();
            int y = sc.nextInt();
            arr.add(new Point(x,y));
        }
        Collections.sort(arr);
        for(Point o : arr) System.out.println(o.x + " " + o.y);
    }
}