7. 좌표 정렬
N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램
정렬기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다.
입력) 첫째 줄에 좌표의 개수인 N(3<=N<=100,000)이 주어집니다.
두 번째 줄부터 N개의 좌표가 x, y 순으로 주어집니다.
출력) N개의 좌표를 정렬하여 출력하세요.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Point implements Comparable<Point> {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point object) { // 오름차순
if (this.x==object.x) return this.y - object.y;
else return this.x - object.x;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ArrayList<Point> arr = new ArrayList<>();
for (int i=0; i<n; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
arr.add(new Point(x,y));
}
Collections.sort(arr); // 정렬
for (Point p : arr) {
System.out.println(p.x + " " + p.y);
}
}
}
Comparable 인터페이스 -> 정렬
결과
입력
5
2 7
1 3
1 2
2 5
3 6
출력
1 2
1 3
2 5
2 7
3 6
'알고리즘(Java) > Sorting & Searching' 카테고리의 다른 글
[알고리즘]Searching - 뮤직비디오(결정 알고리즘) (0) | 2021.08.12 |
---|---|
[알고리즘]Binary Search - 이분검색 (0) | 2021.08.12 |
[알고리즘]Sorting & Searching - 장난꾸러기 (2) | 2021.08.10 |
[알고리즘]Sorting & Searching - 중복 확인 (0) | 2021.08.08 |
[알고리즘]Sorting & Searching - Least Recently Used(LRU 알고리즘) (0) | 2021.08.08 |
댓글