I'm learning ANSI C and for a class I have to implement a merge sort algorithm in it. I'm following the book's guide. But, for some reason I can't have it working.
Only two digits from my list got in the right position. And for the others, new digits are created. I have no idea why this happens, I think it is the way I create the temp arrays L
and R
(I'm using 1.0 / 0.0
to set the last element to +INFINITY
). But I'm not sure if that is the reason.
Here is my code so far:
/* C program for Merge Sort */
#include <stdio.h>
#include <stdlib.h>
void printArray(int A[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
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 + 1], R[n2 + 1];
for (i = 1; i <= n1; i++) {
L[i] = arr[l + i - 1];
}
for (j = 1; j <= n2; j++) {
R[j] = arr[m + j];
}
L[n1 + 1] = 1.0 / 0.0;
R[n2 + 1] = 1.0 / 0.0;
i = 1;
j = 1;
for (k = l; k <= r; k++) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
}
// If I delete this the code stop "working". Why???
while (i < k && k < i) {
i++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int middle = left + (right - left) / 2;
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);
merge(arr, left, middle, right);
}
}
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Also, for some reason beyond my humble understanding when i delete the while
block, that does nothing apparently, the code stops working. Can someone give me a light on this?