
분할 정복(Divide and Conquer) 방식으로 배열을 반씩 나누어 정렬한 후 병합(Merge)하는 방식이다.
평균 : 분할이 균형있게 일어나는 경우
최악 : 피봇이 항상 한 쪽 끝(예: 이미 정렬된 배열)을 선택할 경우
low+high)/2 을 피봇으로 정한다.low 는 피봇보다 큰 값을 만날 때 까지 이동high 는 피봇보다 작은 값을 만날 때까지 이동swaplow 가 high 보다 커질 때까지 반복import java.util.Arrays;
public class QuickSortExample {
public static void solution(int[] arr) {
/* 예시: [5, 3, 8, 9, 2, 4, 7] */
System.out.println("원본 배열 : " + Arrays.toString(arr));
quickSort(arr, 0, arr.length - 1);
System.out.println("정렬된 배열 : " + Arrays.toString(arr));
}
private static void quickSort(int[] arr, int low, int high) {
if (low >= high) return; // 종료 조건: 구간 크기가 1 이하일 때
int partitionIndex = partition(arr, low, high);
// partitionIndex는 오른쪽 구간의 시작점
quickSort(arr, low, partitionIndex - 1); // 왼쪽 구간
quickSort(arr, partitionIndex, high); // 오른쪽 구간
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[(low + high) / 2]; // 가운데 값 선택
System.out.println("Pivot : " + pivot + " | 범위: " + low + " ~ " + high);
System.out.println("분할 전 : " + Arrays.toString(arr));
while (low <= high) {
while (arr[low] < pivot) low++;
while (arr[high] > pivot) high--;
if (low <= high) { // 엇갈리지 않았다면 교환
swap(arr, low, high);
low++;
high--;
}
}
System.out.println("분할 후 : " + Arrays.toString(arr));
System.out.println("반환할 분할 기준 인덱스 : " + low);
System.out.println("===============================");
return low; // 오른쪽 파티션의 시작 인덱스
}
private static void swap(int[] arr, int idx1, int idx2) {
int temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
public static void main(String[] args) {
int[] arr = {5, 3, 8, 9, 2, 4, 7};
solution(arr);
}
}

초록색이 high, 파란색이 low , 빨간색이 partitionIndex이다.