我必须用不同大小的数据测试Mergesort。我遇到的问题是,如果整数数组的大小约为5000000,则我的代码将崩溃,但没有给出错误。我计算了阵列将占用的空间量,如果我没有记错的话,这将是大约0,02 GB,而我的RAM是8GB。我还搜索了数组的最大大小,没有找到任何有用的东西。那么问题出在哪里呢?
/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
#include <time.h>
#define MAX 2000000
int arr[MAX];
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(l, m);
mergeSort(m+1, r);
merge(l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray()
{
int i;
for (i=0; i < MAX; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
srand(time(NULL));
for (int var = 0; var < MAX; ++var) {
arr[var] = rand() % 100;
}
clock_t t1, t2;
//printf("Given array is \n");
// printArray();
t1 = clock();
mergeSort(0, MAX - 1);
t2 = clock();
printf("\nSorted array is \n");
printArray();
float timetaken = t2 - t1;
timetaken /= CLOCKS_PER_SEC;
printf("Time spend: %f\n", timetaken);
return 0;
}
答案 0 :(得分:1)
在
void merge(int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; ...
L和R可能太大而无法放在堆栈中,堆栈的大小受到限制,请执行ulimit-a
来查看限制。
如果这是原因,您将不得不在堆中分配它们( malloc ),并且不要忘记释放它们;-)
当您需要一个大数组,如果它的大小是一个常量(这里不是这种情况),并且使用它的函数既不是直接也不是间接递归的,则可以使用静态var,例如:{{1} },而不是void foo() { ... static int v[4096]; ... }