/**
* @Date: 2020-03-24
* @Description: 快速排序算法(随机选取一个数为基数 , 比他大的总是在右边 , 小的总是在左边)
* @Description: 时间复杂度为O(nlogn)
*/
public static void quickSortRandom(int a[], int low, int high) {
if (low >= high) {
return;
}
int p = randomPartition(a, low, high);
quickSortRandom(a, low, p - 1);
quickSortRandom(a, p + 1, high);
}
public static int randomPartition(int[] a, int left, int right) {
int r = new Random().nextInt(right - left + 1) + left; //生成一个随机数,即是主元所在位置
swap(a, left, r); //将主元与序列最右边元素互换位置,这样就变成了之前快排的形式。
return partitionRandom(a, left, right); //直接调用之前的代码
}
public static int partitionRandom(int[] a, int low, int high) {
int i = low;
int j = high;
int base = a[low];
while (i != j) {
while (a[j] >= base && i < j) {
j--;
}
while (a[i] <= base && i < j) {
i++;
}
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//将a[low] a[i]的值进行交换,因为a[i]始终是比base小的数的最右边的一个数
a[low] = a[i];
a[i] = base;
return i;
}
//交换数组a中的a[i]和a[j]
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}