我正在尝试使用QuickSort制作最多50,000个数字的时间复杂度图表。
对随机数进行排序可以正常工作。当对超过4000个数字的already sorted
数组进行排序时,我得到Debug\QS.exe (process 2208) exited with code -1073741571.
。与分区中位数枢纽配合使用时效果很好。
问题可能出在Function uses '64000' bytes of stack: exceeds /analyze:stacksize '16000'. Consider moving some data to heap.
上。
我的知识很低,所以我用规则数组而不是usind std :: array或vector解决了这个问题。 为了快速排序,我使用了伪代码。我应该如何实施代码来纠正“崩溃”?
编辑:为了以升序生成数组,我首先生成了随机数组,然后对其进行了排序,我相信这是更好的方法。
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
#include <chrono>
#include <functional>
const int size = 50000;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> num(1, 1000000);
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
void generateAscending(int* arr, int size) {
for (int index = 0; index < size; index++) {
arr[index] = num(gen);
}
std::sort(arr, arr + size);
}
bool check(int* arr, int low, int high) {
for (int i = low; i < high - 1; i++) {
if (arr[i + 1] < arr[i]) {
return false;
}
}
return true;
}
int partition(int* arr, int low, int high) {
int pe = arr[low];
int l = low;
int d = high;
while (l < d) {
while (arr[l] <= pe && l < high) l++;
while (arr[d] >= pe && d > low) d--;
if (l < d) {
swap(&arr[l], &arr[d]);
}
}
swap(&arr[low], &arr[d]);
return d;
}
int partition_median(int* arr, int low, int high) {
int m = low + (high - low) / 2; // median pivot
int pe = arr[m];
int l = low;
int d = high;
swap(&arr[low], &arr[m]);
while (l < d) {
while (arr[l] <= pe && l < high) l++;
while (arr[d] >= pe && d > low) d--;
if (l < d) {
swap(&arr[l], &arr[d]);
}
}
swap(&arr[low], &arr[d]);
return d;
}
void quickSort(int* arr, int low, int high) {
if (low < high) {
int j = partition(arr, low, high);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
void quickSort_median(int* arr, int low, int high) {
if (low < high) {
int j = partition_median(arr, low, high);
quickSort_median(arr, low, j - 1);
quickSort_median(arr, j + 1, high);
}
}
int main(int argc, char* argv[]) {
int arr[size];
generateAscending(arr, size);
// Check if in ascending order
if (check(arr, 0, size - 1)) {
std::cout << "Array is in ascending order." << '\n';
}
else {
std::cout << "Array is not in ascending order." << '\n';
}
// Quick sort
auto start = std::chrono::steady_clock::now();
quickSort(arr, 0, size - 1);
auto end = std::chrono::steady_clock::now();
std::cout << "Time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << '\n';
/*
// Quick sort median
auto start = std::chrono::steady_clock::now();
quickSort_median(arr, 0, size - 1);
auto end = std::chrono::steady_clock::now();
std::cout << "Time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << '\n';
*/
if (check(arr, 0, size - 1)) {
std::cout << "Array is in ascending order." << '\n';
}
else {
std::cout << "Array is not in ascending order." << '\n';
}
return 0;
}