0

这是我在大数组中查找频繁数的代码。它适用于 500,000。谁能帮助我并告诉我为什么它会在 n = 2,000,000 时崩溃?

我尝试将 int 更改为 long 或 double 但它崩溃/不允许我编译。

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

int n=500000;
int A[n];
clock_t begin, end; // this is used for measuring the running time
double elapsed_secs;
int ans;


for (int i=0; i<=0.1*(n-1); i++){
    A[i]=n-i;               
}

for (int i=0.1*n; i<n; i++){
    A[i]=1;  
}


/* Now we run the first algorithm, which is always correct.
 */

begin = clock(); // start couting the time
ans = almostUnanimousAlwaysCorrect(A, n);
end = clock(); // end counting the time
elapsed_secs = 1000*double(end - begin) / CLOCKS_PER_SEC;
cout << endl << "(1) The first algorithm (which is always correct) answers "<<endl;

if (ans==1) cout << "1 (correct)\n";
else  cout << "no frequent number (wrong) \n";

cout << "Time taken for the first algorithm is " << elapsed_secs << " milliseconds." << endl<<endl;


/* Now we run the second algorithm, which is NOT always correct.
   Note that the sorting function change how A looks. So, in principle,
   we should reset A. But let's not worry about that for now.
 */

begin = clock(); // start couting the time
ans = almostUnanimousRandom(A, n);


end = clock(); // end counting the time
elapsed_secs = 1000*double(end - begin) / CLOCKS_PER_SEC;
cout << endl << "(2) The second algorithm (which is NOT always correct) answers "<<endl;
if (ans==1) cout << "1 (correct)\n";
else  cout << "no frequent number (wrong) \n";

cout << "Time taken for the second algorithm is " << elapsed_secs << " milliseconds." << endl<<endl;


system("pause");


}
4

1 回答 1

6

您的堆栈内存不足。而是在堆上分配它:

int n=500000;
int* A = new int[n];

然后当你完成它时:

delete[] A;
于 2013-05-05T16:30:41.127 回答