| 1 | import java.util.Arrays; |
| 2 | |
| 3 | public class QuickSort { |
| 4 | |
| 5 | static void quickSort(int[] arr, int start, int end) { |
| 6 | if (start < end) { // 배열의 크기가 충분히 작아 질 때 까지 나눔 |
| 7 | int p = partition(arr, start, end); // 파티션을 적용 했을 때 피봇의 인덱스를 구함 |
| 8 | |
| 9 | quickSort(arr, start, p - 1); // 처음 부터 피봇 전, |
| 10 | quickSort(arr, p + 1, end); // 피봇 후 부터 마지막 까지 다시 퀵소트를 함 |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | static int partition(int[] arr, int start, int end) { |
| 15 | int low = start + 1; // pivot을 맨 왼쪽 값으로 할것이기 때문에 그 다음 값부터 확인 |
| 16 | int high = end; |
| 17 | int pivot = arr[start]; // 가장 왼쪽 값을 pivot으로 설정 |
| 18 | |
| 19 | while (low <= high) { // 양쪽에서 탐색하면서 둘이 겹쳐져 지나칠때 까지 한다. |
| 20 | while (low <= end && arr[low] < pivot) { // 앞에서 부터 비교중 pivot 보다 크면 stop |
| 21 | low++; |
| 22 | } |
| 23 | while (high >= start && arr[high] > pivot) { // 뒤에서 부터 비교중 pivot 보다 작으면 stop |
| 24 | high--; |
| 25 | } |
| 26 | if (low < high) { // low , high 가 겹쳐져 지나친게 아니면 둘을 바꿔줌 |
| 27 | swap(arr, low, high); |
| 28 | } |
| 29 | } |
| 30 | swap(arr, start, high); // 마지막으로 pivot과 high index의 값을 바꾸면 high index 가 pivot의 index가 됨 |
| 31 | |
| 32 | System.out.println(Arrays.toString(arr) + " pivot: " + pivot + " result index: " + high); |
| 33 | |
| 34 | return high; // pivot 위치 반환 |
| 35 | } |
| 36 | |
| 37 | static void swap(int[] arr, int i, int j) { |
| 38 | int temp = arr[j]; |
| 39 | arr[j] = arr[i]; |
| 40 | arr[i] = temp; |
| 41 | } |
| 42 | |
| 43 | public static void main(String[] args) { |
| 44 | int[] arr = { 3, 7, 6, 5, 1, 4, 2 }; |
| 45 | System.out.println(Arrays.toString(arr) + " start"); |
| 46 | |
| 47 | quickSort(arr, 0, 6); |
| 48 | |
| 49 | System.out.println(Arrays.toString(arr) + " finish"); |
| 50 | } |
| 51 | } |
nothing calls this directly
no outgoing calls
no test coverage detected