Now, I do know several versions of merge sort in java that actually work, but for my own sake, I'd like to know why my translation of the c code below is wrong. To me it seems like the logic should be the same. Nevertheless, I have verified that the c code works and that the java code does not.
Here is the original code in c
/* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int *L = (int *)malloc(sizeof(int)*n1); int *R = (int *)malloc(sizeof(int)*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; j = 0; k = l; 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++; } }
Here is my translation into java
void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int []L = new int [n1]; int []R = new int [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; j = 0; k = l; 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++; } }
The error is always at the line R[j] = arr[m + 1+ j];
I thought it might be an off-by one error, so I tried putting in +1 or -1 in a few places, but still couldn't get it to work. Maybe someone here will have more success finding it.
I've heard that c doesn't translate all that well into java (I have virtually no experience with c), but I can't see how the operations used in the two above are all that different.