If you pass the array size to the function as the index of the last element, then everything works as it should. But if you pass the size - 1, then the sorting does not reach the last element. What is the problem?
void merge(int *array, int start, int middle, int end)
{
int i, j, k;
int leftpoint = middle - start;
int rightpoint = end - middle;
if (leftpoint == 0 || rightpoint == 0)
return;
int leftArray[leftpoint];
int rightArray[rightpoint];
for (i = 0; i < leftpoint; i++) {
leftArray[i] = array[start + i];
}
for (j = 0; j < rightpoint; j++) {
rightArray[j] = array[middle + j];
}
i = 0;
j = 0;
for (k = start; k < end; k++) {
if (j == rightpoint || (i < leftpoint && leftArray[i] <= rightArray[j])) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
}
}
void mergeSort(int *arr, int start, int end)
{
int middle;
if (end - start > 1) {
middle = start + (end - start) / 2;
mergeSort(arr, start, middle);
mergeSort(arr, middle, end);
merge(arr, start, middle, end);
}
}