思路
- 随机找数组中一个数做基准数;
- 经过一个partition操作,达到基准数左边的数都比它小,右边的数都比它大。以此固定基准数的位置;
- 基准数左侧部分递归做partition操作;
- 基准数右侧部分递归做partition操作;
- 递归的出口是只剩一个元素。
partition
功能:经过一系列比较交换后,使base基准数左边的数都比它小,右边的数都比它大
流程:
- 规定less下标的左边为小于base的区域,more下标的右边为大于base的区域
- 用index指针遍历元素,从数组的L遍历到R
- 遍历到的数小于base,less右移,less位置和index位置元素交换,index右移
- 遍历到的数等于base index右移
- 遍历到的数大于base,more左移,more位置与index位置元素交换,index不动
代码
/**
* 随机快排
*/
public static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int base = arr[new Random().nextInt(arr.length)];
int[] cut = partition(arr, base, left, right);
quickSort(arr, left, cut[0]);
quickSort(arr, cut[1], right);
}
/**
* partition,即荷兰国旗问题
*/
public static int[] partition(int[] arr, int base, int left, int right) {
int less = left - 1;
int more = right + 1;
int index = left;
while (index < more) {
if (arr[index] < base) {
less++;
exchange(arr, less, index);
index++;
} else if (arr[index] == base) {
index++;
} else {
more--;
exchange(arr, more, index);
}
}
return new int[]{less, more};
}
public static void exchange(int[] arr, int minIndex, int index) {
int temp = arr[minIndex];
arr[minIndex] = arr[index];
arr[index] = temp;
}