C Program for Merge Sort.

// mergesort

#include<stdio.h>

int a[50],n;

int main()

{

   int i;



   printf("How many elements are u going to enter?: ");

   scanf("%d",&n);

   generate(a,n);





   for(i=0;i<n;i++)

    printf("%d ",a[i]);



     msortdiv(0,n-1);

    printf("\nOrder of Sorted elements: ");

   for(i=0;i<n;i++)

      printf(" %d\t",a[i]);



}



int msortdiv(int low,int high)

{

    int mid;

    if(low!=high)

    {

        mid=((low+high)/2);

        msortdiv(low,mid);

        msortdiv(mid+1,high);

        mergesort(low,mid,high);

    }



}

int mergesort(int low,int mid,int high)

{

    int t[50],i,j,k;

    i=low;

    j=mid+1;

    k=low;

    while((i<=mid) && (j<=high))

    {

        if(a[i]>=a[j])

            t[k++]=a[j++];

        else

            t[k++]=a[i++];

    }

    while(i<=mid)

        t[k++]=a[i++];



    while(j<=high)

        t[k++]=a[j++];

    for(i=low;i<=high;i++)

        a[i]=t[i];

}



void generate(int a[],int n)

{

int i;

for(i=0;i<n;i++)

   a[i]=rand()%100;



}

Post a Comment

3 Comments

Thanks,To visit this blog.