mardi 6 juin 2017

Same code but Strange behaviour

This is my code on implementation of merge sort , it is showing no error at all and giving no output either :

#include<iostream>

using namespace std;

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],R[n2];

    for(i=0;i<n1;i++)
    {
        L[i]=arr[i+l];
    }

    for(j=0;j<n2;j++)
    {
        R[j]=arr[m+1+j];
    }

    i=0;
    j=0;
    k=1;

    while(i<n1 && j<n2)
    {
        if(L[i]<=R[j])
        {
            arr[k]=L[i];
            i++;
        }
        else
        {
            arr[k]=R[j];
            j++;
        }
        k++;
    }

    while(i<n1)
    {
        arr[k]=L[i];
        i++;
        k++;
    }

    while(j<n2)
    {
        arr[k]=R[j];
        j++;
        k++;
    }

}

void mergeSort(int arr[], int l, int r)
{
    if(l < r)
    {

        int m = l+(r-1)/2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

void printArray(int A[],int size)
{
    int i;
   for( i=0;i<size;i++)
        cout<<A[i]<<" ";
}

int main()
{
    int arr[]={12,65,34,78,90,65,34};
    int arr_size = sizeof(arr)/sizeof(arr[0]);

    cout<<"Given array is \n";
    printArray(arr, arr_size);

    mergeSort(arr, 0, arr_size - 1);

    cout<<"\nSorted array is \n";
    printArray(arr, arr_size);
return 0;
}

now here is the piece of code , which is the problem :

void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {


        int m = l+(r-l)/2;


        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

if i replace this mergeSort code with the above program's mergeSort, the program gives output. but have a look , both mergeSort codes are same (in program code as well as mentioned mergeSort code)

link to original code ===> http://cpp.sh/6zdip

link to the code after replacing mergeSort ====> http://cpp.sh/7lfo

this is most strange problem ,i have ever faced.

Aucun commentaire:

Enregistrer un commentaire