You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入量超50万时代码异常退出,求排序算法运行时长测试解决方案

问题解决办法

核心原因

你的代码里使用了变长数组(VLA) int a[size];,这类数组在栈(Stack)上分配内存。栈的默认空间通常很小(比如Windows下默认1MB,Linux下默认8MB),当size超过50万时,数组所需的内存(500000 * 4字节 = 2000000字节 ≈ 2MB)会超出栈的容量,直接引发栈溢出,导致程序崩溃退出且无输出。

另外,你采用的冒泡排序时间复杂度为O(n²),50万级别的数据排序会耗时极久——即便解决了内存问题,也可能需要等待很长时间才能看到结果。

具体修复方案

方案1:动态内存分配(手动管理)

将栈上数组改为在堆(Heap)上分配,堆的可用空间远大于栈:

int size;
cout << "Enter size of the array: " << endl;
cin >> size;
// 在堆上分配数组
int* a = new int[size];
for(int i=0;i<size;i++)
{
    a[i] = rand() % size;
}
int temp = 0;
double cl = clock();
// 冒泡排序逻辑保持不变
for (int i = 0; i < size; i++)
{
    for (int j = i + 1; j < size; j++)
    {
        if (a[j] < a[i])
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
}
double final = clock() - cl;
cout << final / (double)CLOCKS_PER_SEC << endl;
// 释放堆内存,避免内存泄漏
delete[] a;

方案2:使用标准容器vector(推荐)

vector会自动在堆上分配内存,且无需手动管理内存生命周期:

#include <vector> // 需要包含vector头文件

int size;
cout << "Enter size of the array: " << endl;
cin >> size;
vector<int> a(size);
for(int i=0;i<size;i++)
{
    a[i] = rand() % size;
}
int temp = 0;
double cl = clock();
// vector用法与数组一致,排序逻辑不变
for (int i = 0; i < size; i++)
{
    for (int j = i + 1; j < size; j++)
    {
        if (a[j] < a[i])
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
}
double final = clock() - cl;
cout << final / (double)CLOCKS_PER_SEC << endl;

额外优化:替换冒泡排序

若仅为测试排序时长,建议用时间复杂度*O(n log n)*的算法替代冒泡排序,比如标准库的std::sort:

#include <vector>
#include <algorithm> // 包含sort头文件

int size;
cout << "Enter size of the array: " << endl;
cin >> size;
vector<int> a(size);
for(int i=0;i<size;i++)
{
    a[i] = rand() % size;
}
double cl = clock();
sort(a.begin(), a.end()); // 使用标准库排序函数
double final = clock() - cl;
cout << final / (double)CLOCKS_PER_SEC << endl;

内容的提问来源于stack exchange,提问作者Ali Hasan Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:20:21