Merge Sort на C. Неверная работа верного алгоритма
В ходе написания алгоритма Merge Sort на языке C возникла проблема с выходными данными. Сам алгоритм описан верно, что уже многократно проверил, но выходные данные не соответствуют ожидаемому результату.
#include <stdio.h>
#include <stdlib.h>
void error(const unsigned uCode);
void get_array(int* nTargetArray, const size_t nLength);
void set_array(int* nTargetArray, const size_t nLength);
void merge(int nTargetArray[], const size_t nBegin, const size_t nMiddle, const size_t nEnd);
void merge_sort(int* nTargetArray, const size_t nBegin, const size_t nEnd);
int main(const int argc, const char** const argv, const char** const envp)
{
const size_t nLength = 12;//atoi(argv[1]);
int* nArray = (int*) malloc((uLength) * sizeof(int));
if(!nArray) error(1);
set_array(nArray, uLength);
get_array(nArray, nLength);
// merge_sort doesn't work correct
merge_sort(nArray, 0, nLength - 1);
get_array(nArray, nLength);
free((void*) nArray);
return 0;
}
void error(const unsigned uCode)
{
switch(uCode)
{
case 1:
printf("A\040segmentation\040error\040occurred.\r\n");
break;
default:
printf("An\040error\040occurred.\r\n");
break;
}
exit(0);
}
void* get_array(int* nTargetArray, const size_t nLength)
{
if(!nTargetArray) error(1);
for (size_t i = 0; i < nLength; i++)
printf("%d\040", nTargetArray[i]);
printf("\r\n");
return;
}
void* set_array(int* nTargetArray, const size_t nLength)
{
if(!nTargetArray) error(1);
printf("Enter an integer sequence[a, b, ..]: ");
for(size_t i = 0; i < nLength; i++)
scanf("%d", &nTargetArray[i]);
return;
}
void merge_sort(int* nTargetArray, const size_t nBegin, const size_t nEnd)
{
if(nBegin < nEnd)
{
const size_t nMiddle = nBegin + (nEnd - nBegin) / 2;
merge_sort(nTargetArray, nBegin, nMiddle);
merge_sort(nTargetArray, nMiddle + 1, nEnd);
merge(nTargetArray, nBegin, nMiddle, nEnd);
}
return;
}
void merge(int nTargetArray[], const size_t nBegin, const size_t nMiddle, const size_t nEnd)
{
int i, j, k;
unsigned uLeftSize = nMiddle - nBegin + 1;
unsigned uRightSize = nEnd - nMiddle;
int nLeftArray[uLeftSize];
int nRightArray[uRightSize];
for(i = 0; i < uLeftSize; i++)
nLeftArray[i] = nTargetArray[nBegin + i];
for(j = 0; j < uRightSize; j++)
nRightArray[j] = nTargetArray[nMiddle + 1 + j];
i = 0;
j = 0;
k = 0;
while(i < uLeftSize && j < uRightSize)
{
if(nLeftArray[i] <= nRightArray[j])
{
nTargetArray[k] = nLeftArray[i];
i++;
} else
{
nTargetArray[k] = nRightArray[j];
j++;
}
k++;
} // End of while.
// Copy the remaining elements of left array, if there are any.
while(i < uLeftSize)
{
nTargetArray[k] = nLeftArray[i];
i++;
k++;
}
// Copy the remaining elements of right array, if there are any.
while(j < uRightSize)
{
nTargetArray[k] = nRightArray[j];
j++;
k++;
}
return;
}
Буду невероятно признателен тому, кто объяснит, в чём заключается проблема.