기술 블로그

Java vector sort 본문

JAVA

Java vector sort

parkit 2020. 1. 8. 18:08
728x90
반응형

C++ vector에서도 cmp 함수를 구현하는 것처럼 Java에서도 비슷하다.




연습문제 : https://www.acmicpc.net/problem/11650




아래는


First 먼저 오름차순 

(First가 같으면) Second 오름차순


의 구현이다.




1
2
3
4
5
6
7
8
9
10
11
12
13
Collections.sort(v, new Comparator<Pair>() {
            public int compare(Pair p1, Pair p2) {
                if(p1.First < p2.First) {
                    return -1;
                }
                else if(p1.First == p2.First) {
                    return Integer.compare(p1.Second, p2.Second);
                }
                else {
                    return 1;
                }
            }
        });
cs






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.io.*;
import java.util.*;
 
public class Main {
    
    static int n;
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st;
        
        Vector<Pair> v = new Vector<Pair>();
        
        n = Integer.parseInt(br.readLine());
        
        int x, y;
        
        for(int i=0; i<n; i++) {
            st = new StringTokenizer(br.readLine());
            
            x = Integer.parseInt(st.nextToken());
            y = Integer.parseInt(st.nextToken());
            
            v.add(new Pair(x, y));
        }
        
        Collections.sort(v, new Comparator<Pair>() {
            public int compare(Pair p1, Pair p2) {
                if(p1.First < p2.First) {
                    return -1;
                }
                else if(p1.First == p2.First) {
                    return Integer.compare(p1.Second, p2.Second);
                }
                else {
                    return 1;
                }
            }
        });
        
        for(Pair i : v) {
            System.out.println(i.First + " " + i.Second);
        }
    }
}
 
class Pair {
    
    int First, Second;
    
    Pair(int first, int second) {
        this.First = first;
        this.Second = second;
    }
}
cs


















728x90
반응형