C++随机快速排序,代码能跑,但是结果不对。
#include <iostream>
#include <vector>
#include <random>
using namespace std;
// 交换函数
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 分区函数
int partition(vector<int>& arr, int low, int high) {
// 随机选择一个元素作为基准元素
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, high);
int pivot = arr[dis(gen)];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// 快速排序函数
void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
vector<int> arr = {8, 45, 0, 30, 49, 16, 20, 20};
int n = arr.size();
cout << "排序前的数组:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
quickSort(arr, 0, n - 1);
cout << endl << "排序后的数组:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
输出:
排序前的数组:8 45 0 30 49 16 20 20
排序后的数组:8 0 16 20 45 20 30 49