快速排序不适用于大型数组

Quicksort does not work with large arrays

本文关键字:数组 大型 适用于 不适用 快速排序      更新时间:2023-10-16

我正在尝试使用快速排序和合并排序对大型数组进行排序以评估性能。

我有一个问题:如果我在数组中强加大量元素,程序不会开始随机生成值。在下面的代码中,如果N=500000,它运行良好。如果N > 500000,例如1000000,则不起作用。使用合并排序,限制为200000。我在多个设备上尝试过,C++在Eclipse IDE上。

有人知道如何解决问题吗?

#define N 800000
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <chrono>
using namespace std;
void Exchange(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int Partition(int A[], int p, int r) {
int x = A[r];
int i = p - 1;
for (int j = p; j <= r; j++) {
if (A[j] < x) {
i++;
Exchange(&A[i], &A[j]);
}
}
Exchange(&A[i + 1], &A[r]);
return i + 1;
}
int RPartition(int A[], int p, int r) {
srand(time(NULL));
int i = p + rand() % (p - r);
Exchange(&A[i], &A[r]);
return Partition(A, p, r);
}
void QuickSort(int A[], int p, int r) {
if (p < r) {
int q = RPartition(A, p, r);
QuickSort(A, p, q - 1);
QuickSort(A, q + 1, r);
}
}
void Stampa(int A[], int n) {
for (int i = 0; i < n; i++) {
cout << A[i] << "n";
}
}
int main() {
srand(50000);
int A[N];
for (int i = 0; i < N; i++) {
A[i] = rand();
}
cout << "Array non ordinaton";
Stampa(A, N);
auto start = std::chrono::system_clock::now();
QuickSort(A, 0, N - 1);
auto end = std::chrono::system_clock::now();
cout << "nArray ordinaton";
Stampa(A, N);
std::chrono::duration<double> elapsed = end - start;
cout << "Elapsed time: " << elapsed.count() << "s";
}

解释非常简单:您将数组分配为具有自动存储的局部变量(即在堆栈上(,因此如果大小太大,则会出现堆栈溢出

应从堆中分配数组或将其定义为静态数据。

这是一个修改版本:

int main() {
srand(time(NULL));
int *A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = rand();
}
cout << "Array non ordinaton";
Stampa(A, N);
auto start = std::chrono::system_clock::now();
QuickSort(A, 0, N - 1);
auto end = std::chrono::system_clock::now();
cout << "nArray ordinaton";
Stampa(A, N);
std::chrono::duration<double> elapsed = end - start;
cout << "Elapsed time: " << elapsed.count() << "s";
delete[] A;
}