package demo;
public class QuickSortDemo {
public static void main(String[] args) {
int[] arr = new int[] {1, 2, 5, 4, 6};
quickSort(arr, 0, arr.length - 1);
for(int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int postion = findPostion(arr, left, right);
quickSort(arr, left, postion - 1);
quickSort(arr, postion + 1, right);
}
}
public static int findPostion(int[] arr, int left, int right) {
// 把最左元素当作基准
int pivot = arr[left];
while(left < right) {
// right向左移动,直到遇到比pivot小的
while(left < right && arr[right] >= pivot) {
right--;
}
arr[left] = arr[right];
// left向右移动,直到遇到比pivot大的
while(left < right && arr[left] < pivot) {
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}
}