Merge Sort using Array


#include<stdio.h>
#include<conio.h>

void merge(int *arr,int top,int size,int bottom)
{
    int tmp[50],f=top,s=size+1,t=top,upper;
        while((f<=size)&&(s<=bottom))
        {
           if(arr[f]<=arr[s])
           {
                tmp[t++]=arr[f];
                f++;
           }
           else
            {
             tmp[t++]=arr[s];
             s++;
            }

        }
        if(f<=size)
        {
          for(f=f;f<=size;f++)
          {
           tmp[t]=arr[f];
           t++;
          }
        }
        if(s<=bottom)
        {
            for(s=s;s<=bottom;s++)
            {
            tmp[t]=arr[s];
            t++;
            }
        }
        for(upper=top;upper<=bottom;upper++)
        arr[upper]=tmp[upper];
}

void mergesort(int *arr,int low,int high)
{
    int mid;
    if(low!=high)
    {
        mid=(low+high)/2;
        mergesort(arr,low,mid);
        mergesort(arr,mid+1,high);
        merge(arr,low,mid,high);
    }
}

void main()
{
  int n,i,*arr;
    printf("\nEnter the size of the array:");
    scanf("%d",&n);
    arr=(int*)malloc(sizeof(int)*n);
    printf("\nEnter any %d numbers:\n",n);
    for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
    i=0;
    mergesort(arr,i,n-1);
    printf("\nSorted Array:");
    for(i=0;i<n;i++)
    printf(" %d ",arr[i]);
  getch();
  }



No comments: