import java.util.Random;
public class Main {
Random random = new Random();
//产生随机数组用于测试
int[] generateList() {
int N = random.nextInt(100) + 10;
int[] a = new int[N];
for (int i = 0; i < a.length; i++) {
a[i] = random.nextInt(1000);
}
return a;
}
//判断数组a是否升序
boolean checkRight(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) return false;
}
return true;
}
//随机化快排
void quickSort(int[] a, int beg, int end) {
//递归终止条件
if (end <= beg) return;
//随机选择分界值,并把分界值移动到最左边
int x = random.nextInt(end - beg) + beg;
int sep = a[x];
a[x] = a[beg];
a[beg] = sep;
//双指针交替移动,直到相遇,复杂度为O(N),无额外空间
int l = beg, r = end - 1;
while (true) {
//先移动右边的指针,直到找到小于sep的值
while (r > l && a[r] >= sep) r--;
if (r <= l) break;
a[l] = a[r];
a[r] = sep;
l++;
//移动功能左边的指针,直到找到大于sep的值
while (l < r && a[l] <= sep) l++;
if (l >= r) break;
a[r] = a[l];
a[l] = sep;
r--;
}
quickSort(a, beg, l);
quickSort(a, l + 1, end);
}
Main() {
for (int i = 0; i < 100; i++) {
int[] a = generateList();
quickSort(a, 0, a.length);
if (!checkRight(a)) {
System.out.println("wrong");
}
}
}
public static void main(String[] args) {
new Main();
}
}