点击查看代码
#include<cstdio>
#include<stdlib.h> //使用srand()和rand()
#include<time.h> //使用time()
#include<cmath> //使用round()
#include<algorithm> //使用std::swap()
#pragma warning(disable:4996)
//对区间[left,right]进行划分
int randPartition(int A[], int left, int right) {
//生成[left,right]范围内的随机数p
int p = (round(1.0 * rand() / RAND_MAX * (right - left) + left));
std::swap(A[p], A[left]); //将随机数A[p]作为分界点A[left]
int temp = A[left];
while (left < right) {
while (left < right && A[right] > temp) right--;
A[left] = A[right];
while (left < right && A[left] <= temp) left++;
A[right] = A[left];
}
A[left] = temp;
return left;
}
//随机快速排序,left和right初始值为序列首尾下标
void quickSort(int A[], int left, int right) {
if (left < right) { //区间长度小于1就进行划分
//将区间[left,right]按A[left]一分为二
int pos = randPartition(A, left, right);
quickSort(A, left, pos - 1); //对[left,pos-1]区间进行快排
quickSort(A, pos + 1, right); //对[pos+1,right]区间进行快排
}
}
int main() {
srand((unsigned)time(NULL)); //生成随机数的种子
return 0;
}