Sort

보보캉·2021년 3월 2일
0

Algorithm

목록 보기
2/18

Class에 compareTo를 정의하여 정렬하기

static class Node implements Comparable<Node> {
    int end;
    int cost;
    public Node(int end, int cost) {
    	this.end = end;
        this.cost = cost;
    }
    @Override
    public int compareTo(Node o){
    	return Integer.compare(this.cost, o.cost);
        
        //return this.cost - o.cost; // 오름차순
        // return 값이 음수나 0이면 유지, 양수이면 객체 swap
    }
}

Collections.sort(nodeList);

Comparator를 이용하여 정렬하기

Collections.sort(nodeList, new Comparator<Node>() {
    @Override
    public int compare(Node o1, Node o2) {
    	return Integer.compare(o1.cost, o2.cost);
    }
})
profile
Developer

0개의 댓글