2/23/2009

C Program To Perform Merge_Sort On An Array


/* C Program To Perform Merge_Sort On An Array */
#include<stdio.h>
#include<conio.h>
void simple_merge(int a[],int low,int mid,int high)
{
 int i=low,j=mid+1,k=low,c[10];

  while(i<=mid&&j<=high)
    {
       if(a[i]<a[j])
    {
     c[k]=a[i];
     i=i+1;
     k=k+1;
    }
       else
    {
      c[k]=a[j];
      j=j+1;
      k=k+1;
    }
    }

  while(i<=mid)
   {
   c[k++]=a[i++];
   }

  while(j<=high)
   {
     c[k++]=a[j++];
   }
  for(i=low;i<=high;i++)
   {
     a[i]=c[i];
   }
}

void merge_sort(int a[],int low,int high)
{
       int mid;

       if(low<high)
 {
    mid=(low+high)/2;
    merge_sort(a,low,mid);
    merge_sort(a,mid+1,high);
    simple_merge(a,low,mid,high);
 }
}

void main()
{
   int a[10],n,i;
   clrscr();
    printf("Enter the number of element\n");
  scanf("%d",&n);
    printf("Enter the elements \n");
    for(i=0;i<n;i++)
  scanf("%d",&a[i]);

  merge_sort(a,0,n-1);

  printf("Sorted array is\n");
  for(i=0;i<n;i++)
  printf("%d ",a[i]);
   getch();
}
Out Put:
C Program To Perform Merge_Sort On Array

No comments:

Post a Comment