Question: C Programming Help with merge sorting large file Need help with my C merge sort program, keeps crashing at < 100000 ints The program does

C Programming Help with merge sorting large file

Need help with my C merge sort program, keeps crashing at < 100000 ints

The program does exactly what it is supposed to at anything below 100k integers. After that, it crashes. Im not sure if im allocating memory correctly or what is happening.

Im defining Z at the top to equal 1000000. I get no compiling errors. Please help, will rate immediately.

//Jamie Jackson #include #include int count = 0; #define z 100000 //int arr[z]; void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++) L[i] = arr[l + i];

for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j];

i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; count++; } else { arr[k] = R[j]; j++; count++; } k++;

}

while (i < n1) { arr[k] = L[i]; i++; k++; count++; }

while (j < n2) { arr[k] = R[j]; j++; k++; count++; } }

void mergeSort(int arr[], int l, int r) { if (l < r) {

int m = l+(r-l)/2;

mergeSort(arr, l, m); mergeSort(arr, m+1, r);

merge(arr, l, m, r); } }

void printArray(int A[], int size) { int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf(" "); }

int main(void) {

int i; FILE *myFile; int *arr = (int *) malloc(z * sizeof(int)); myFile = fopen("alg.txt", "r"); int arr_size = z; for(i=0; i < z; i++) { fscanf(myFile, "%d,", &arr[i]); }

mergeSort(arr, 0, arr_size - 1);

printf(" Sorted array is "); printArray(arr, arr_size); printf("count is %d ", count); return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!