프로그래밍 언어/JAVA

백준 > 2751 수 정렬하기 2

B612 2022. 2. 23. 15:41
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
57
58
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Random;
 
public class Main {
    public static int partition(int arr[], int begin, int end) {
        Random ran = new Random();
 
        int pivot = arr[ran.nextInt(end - begin) + begin];
        int temp = 0;
        
        while (begin < end) {
            while ((arr[begin] < pivot) && (begin < end)) {
                begin++;
            }
            while ((arr[end] > pivot) && (begin < end)) {
                end--;
            }
            if (begin < end) {
                temp = arr[begin];
                arr[begin] = arr[end];
                arr[end] = temp;
            }
        }
        return begin;
    }
    
    public static void quicksort (int arr[], int begin, int end) {
        if (begin < end) {
            int p = partition(arr, begin, end);
            quicksort(arr, begin, p - 1);
            quicksort(arr, p + 1, end);
        }
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int n = Integer.parseInt(bf.readLine());
        int[] arr = new int[n];
        
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(bf.readLine());
        }
        
        quicksort(arr, 0, arr.length - 1);
        
        for (int s : arr) {
            bw.write(s + " ");
        }
        bw.flush();
        bw.close();
    }
}
cs

시간 초과가 꽤 났던 문제다. 자바로 문제 푼 지 얼마 되지 않았지만 뭔가 느리기로 악명 높다는 글들을 여러 개 본 적은 있었기 때문에 검색해봤다.

 

-> 자바의 Scanner는 입력 속도가 느리다 따라서 BufferedReader을 쓰는 게 추천된다.

퀵 정렬, BufferedReader 등에 대해 알게 되었다!

'프로그래밍 언어 > JAVA' 카테고리의 다른 글

백준 > 1676 팩토리얼 0의 개수  (0) 2022.02.24
백준 > 2798 블랙잭  (0) 2022.02.24
백준 > 11866 요세푸스 문제 0  (0) 2022.02.22