Сортировка слиянием, выдающая неправильный вывод с некоторыми новыми элементами, которых не было во входном массиве (в C) - PullRequest
0 голосов
/ 20 апреля 2020
void merge(int* a,int* l,int* r,int nl,int nr)
{
    int i=0,j=0,k=0;
    int n=nl+nr;
    while((i<nl)&&(j<nr))
    {
        if(l[i]<r[])
        {
            a[k]=l[i];
            i++;
        }
        else
        {
            a[k]=r[j];
            j++;
        }
        k++;
    }
    while(i<nl)
    {
        a[k]=l[i];
        k++;
        i++;
    }
    while(j<nr)
    {
        a[k]=r[i];
        k++;
        j++;
    }
}

void mergesort(int* a,int n)
{
    if(n<2)
        return;
    int mid;
    mid=n/2;
    int nl=mid;
    int *l;
    int *r;
    int nr=n-mid;
    l=(int*)malloc(sizeof(int)*nl);
    r=(int*)malloc(sizeof(int)*nr);
    int i;
    for(i=0;i<mid;i++)
    {
        l[i]=a[i];
    }
    for(i=mid;i<n;i++)
    {
        r[i-mid]=a[i];
    }
    mergesort(l,nl);
    mergesort(r,nr);
    merge(a,l,r,nl,nr);
    free(l);
    free(r);
} 
void main()
{
    int array[8]={3,2,8,1,4,5,6,9};
    mergesort(array,8); //calling the function
    printf("Sorted Array:\n");
    int i;
    for(i=0;i<8;i++)
    {
        printf("%d ",array[i]);          // Printing The sorted array
    }
}

Приведенная выше программа C дает мне вывод 1 2 3 -1337063635 -1337063603 -1337063603 -1337063603 -1337063603 . Я опустил основной сегмент. Я уверен в своем понимании алгоритма, но я сталкиваюсь с ошибкой, когда внедряю его в C. Я не получаю никаких ошибок или предупреждений в моем компиляторе. Это потому, что у меня проблема с использованием функции Heap для mergesort ()? Детали:

 *The merge function merges the divided arrays. 
 *It takes as input the base pointers to the 2 arrays that need to be merged and their respective sizes.
 *It does not return any value because it works on the array of the calling function (mergesort) itself.

 *The mergesort function takes as input the base pointer of the array that needs to be sorted and the size of the array.
 *It does not return anything but rather uses heap to store the left and right divided arrays.
 *And it uses the merge function to merge the left and right arrays and store it in the calling function.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...