728x90
반응형
퀵정렬
pivot을 이용해서 좌, 우측으로 정렬하는 기법
pivot은 맨 앞, 중간, 맨 뒤 등 임의로 설정할 수 있다.
평균 O(nlogn), 최악일 경우 O(n^2)의 시간 복잡도를 가진다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static int[] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
arr = new int[N];
for (int i=0; i<arr.length; i++) arr[i] = Integer.parseInt(br.readLine());
quickSort(0, N-1);
for (int a : arr) System.out.println(a);
}
public static void quickSort(int start, int end) {
int pivot = arr[(start + end) / 2];
int left = start, right = end;
if (start >= end) return; // 종료 조건
while (left <= right) {
while (arr[left] < pivot) left++;
while (arr[right] > pivot) right--;
if (left <= right) {
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
if (start < right) quickSort(start, right);
if (left < end) quickSort(left, end);
}
}
728x90
반응형
'Develop > Coding Test | Algorithm' 카테고리의 다른 글
[백준] JAVA 풀이 - 1181 : 단어 정렬 (0) | 2024.03.15 |
---|---|
[백준] JAVA 풀이 - 10989 : 수 정렬하기 3 (0) | 2024.03.14 |
[알고리즘] 해시 함수 (Hash Function) (0) | 2024.03.12 |
[알고리즘] 유클리드 호제법 - 최대공약수 / 최소공배수 구하기 (0) | 2024.03.12 |
[백준] JAVA풀이 - 1978 : 소수 찾기 (0) | 2024.03.11 |
댓글