先完成 partition就是一次分割(先写死)。返回中间数,修改partition参数为任意位置。然后递归调用。最后优化为随机数防止退化为O(n^2)。
public class QuickSort02 {
public static void main(String[] args) {
int[] testArray = new int[]{2,2,1,1,3,6,4,7,9,8};
quickSort(testArray, 0, testArray.length - 1);
System.out.printf(Arrays.toString(testArray));
}
private static void quickSort(int[] testArray, int begin, int end) {
if (end - begin < 1){
return;
}
int i = partition(testArray, begin, end);
quickSort(testArray,begin,i-1);
quickSort(testArray,i+1,end);
}
private static int partition(int[] arr,int begin,int end){
int tar = (int) (Math.random()*(end - begin)) + begin;
int left = begin;
int right = end;
while (left < right){
while (left <= end && arr[left] <= arr[tar]) left++;
while (right >= begin && arr[right] > arr[tar]) right--;
if(left < right){
swap(arr,left,right);
}
}
swap(arr,tar,right);
return right;
}
public static void swap(int[] arr,int a,int b){
int tem = arr[a];
arr[a] = arr[b];
arr[b] = tem;
}
}