알고리즘-정렬(sort)

이호영·2022년 1월 17일
0

알고리즘

목록 보기
2/4

오름차순: 작은 값부터 높은 값으로
내림차순: 큰 값 부터 작은 값으로
조건
1. 정렬 조건 어떤 값이 먼저 어느 순으로 정렬할 것 인지
2. 시간복잡도는 약 O(N log N)이다.
3. In-place/ Stable 여부를 알아야한다.
In-place:정렬 과정에서 원소의 개수에 비해서 무시할만한 메모리 개수만 추가로 사용하는지(Quick sort)
Stable: 동등한 위상의 원소들의 순서관계가 보존되는지
비교 불과 관계일경우 입력순서에따라 정렬(Tim sort)
특성
1. 같은 정보들은 정렬 후 인접해있을 것

예제(boj 10825)

import java.util.*;
import java.io.*;

public class sort {
    static FastReader fr= new FastReader();
    static StringBuilder sb= new StringBuilder();

    static class Elem implements Comparable<Elem>{
        public String name;
        public int kr, eng, math;

        @Override
        public int compareTo(Elem other) {
            if(kr != other.kr) return other.kr-kr; //내림차순
            if(eng != other.eng) return eng-other.eng; //오름차순
            if(math != other.math) return math-other.math; //오름차순
            return name.compareTo(other.name);
        }
    }
    static int N;
    static Elem[] a;

    static void input(){
        N=fr.nextInt();
        a=new Elem[N];

        for(int i=0;i<N;i++){
            a[i]=new Elem();
            a[i].name=fr.next();
            a[i].kr=fr.nextInt();
            a[i].eng=fr.nextInt();
            a[i].math=fr.nextInt();
        }
    }
    static void pro(){
        Arrays.sort(a);
        for(int i=0;i<a.length;i++){
            sb.append(a[i].name).append("\n");
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        input();
        pro();
    }
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

0개의 댓글