I will provide you with two files in C language, the first is mergesort.c which is not…
- User
I will provide you with two files in C language, the first is mergesort.c which is not working, and the second is sorting.c which works perfectly well. I want you to find the mistake made in mergesort.c that doesnt makes performs exactly as sorting.c I dont want observations about naming conventions but the root cause, the main reason that it is performing the merge sort algorithm.
// mergesort.c
#include <stdio.h>
void merge(int array[], int left, int mid, int right); void merge_sort(int array[], int left, int right); void print_array(int array[], int size);
int main(void) { int arr[] = { 4, 0, 6, 0, 0, 66, 65, 54, 33, 22, 14, 11, 10, 996, 54, 633, 233, 662, 331, 66, 52, 31, 699, 995, 1026, 3056, 6094, 4032, 4020, 1032, 1021, 1010}; int size = sizeof(arr) / sizeof(arr[0]);
codeprintf("Before: "); print_array(arr, size); // Compute merge_sort(arr, 0, size - 1); printf("After: "); print_array(arr, size);}
void merge(int array[], int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid;
codeint L[n1], R[n2]; for (int i = 0; i < n1; i++) { L[i] = array[left + i]; } for (int j = 0; j < n2; j++) { R[j] = array[right - mid + j]; } int i = 0; int j = 0; int k = left; while (i < n1 && j < n2) { if (L[i] < R[j]) { array[k] = L[i]; i++; } else { array[k] = R[j]; j++; } k++; } while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = R[j]; j++; k++; }}
void merge_sort(int array[], int left, int right) { if (left < right) { int mid = left + (right - left) / 2;
codemerge_sort(array, left, mid); merge_sort(array, mid + 1, right); merge(array, left, mid, right); }}
void print_array(int array[], int size) { for (int i = 0; i < size; i++) { printf("%i ", array[i]); } printf("\n"); }
// sorting.c
#include <stdio.h>
// Function to merge two halves void merge(int arr[], int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid;
Assistant
The main reason why the merge sort in
mergesort.cis not working correctly is because of the incorrect indexing in themergefunction.In the
mergefunction ofmergesort.c, when you're copying the elements fromLandRarrays to the original array, you're starting from indexleftinstead ofmid + 1. This is incorrect because theRarray starts frommid + 1index, notmidindex.The correct indexing in the
mergefunction should be as follows:carray[k] = L[i]; i++; k++;And
carray[k] = R[j]; j++; k++;This is because
Larray starts from indexleft, andRarray starts frommid + 1. Whenkis equal tomid + 1, we start copying elements fromRarray.