快速排序不适用于大型数组
Quicksort does not work with large arrays
我正在尝试使用快速排序和合并排序对大型数组进行排序以评估性能。
我有一个问题:如果我在数组中强加大量元素,程序不会开始随机生成值。在下面的代码中,如果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;
}
相关文章:
- 在堆栈上C++大型多维数组
- 适用于大型数组的无复制线程安全环形缓冲区
- 为大型数组提供堆大小的编译器
- 快速排序不适用于大型数组
- 如何在C++中创建大型数组(如60亿)?
- 为什么优化大型 std::vector 数组会导致 SegFault?
- Excel 不愉快地显示大型 2D 范围公式数组
- 为什么我的代码无法处理大型数组输入(>10000)?
- 在 C++ 中,用于将大型 2D 数组转换为 1D 数组的内存分配
- 在能够从 Web 浏览器访问大型数组数据的同时存储它的最可行方法是什么?
- 将大型 csv 文件读入数组 c++ 中
- 有效地从文本文件中读取带有字符串索引的大型二维数组(矩阵)
- 将大型二维数组初始化为C++中的所有值
- C/C++ 从 STM32 中的另一个类获取大型数据,如 180 数组
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 如何在C++中分配大型动态数组
- 在C 中声明具有默认值的大型数组
- C 大型2D数组(在堆上)崩溃了应用程序
- 提高访问大型数组元素的性能
- 如何使用特征库将大型 2D 数组转换为稀疏矩阵