[자료구조] QuickSort(퀵정렬) - Java

1. QuickSort(퀵정렬)

1.1 퀵정렬 이란?

  1. 배열중에 임의의 한 값을 선택해 그 기준값을 기준으로 작은건 왼쪽, 큰건 오른쪽에 정렬.

문제.2751 [백준] 수 정렬하기 2

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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
br.close();
quickSort(arr);
for (int i : arr) {
System.out.println(i);
}
}

public static void quickSort(int[] arr) {
sort(arr, 0, arr.length - 1);
}

private static void sort(int[] arr, int start, int end) {
if (start >= end)
return;

int mid = partition(arr, start, end);
sort(arr, start, mid - 1);
sort(arr, mid, end);
}

private static int partition(int[] arr, int start, int end) {
int pivot = arr[(start + end) / 2];
while (start <= end) {
while (arr[start] < pivot)
start++;
while (arr[end] > pivot)
end--;
if (start <= end) {
swap(arr, start, end);
start++;
end--;
}
}
return start;
}

private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
  • 4,3,2,1,0 배열을 정렬할때 아래 순으로 졍렬된다.
4 3 2 1 0
0 3 2 1 4
0 1 2 3 4

댓글

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×