Sunday 23 June 2013

Merge Sort C Code

Merge Sort

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

int c[10],k;

void merge(int *a,int u,int l,int n)
{int i;
     k=u;
     int st=u;
     while(u<l && l<=n)
     {
                      if(a[u]<=a[l])
                      {
                          c[k]=a[u];        
                          u++;
                          k++;
                      }
                      else
                      {
                          c[k]=a[l];
                          k++;
                          l++;
     }
}
     while(u<l)
     {
                c[k]=a[u];        
                u++;
                k++;
     }
     while(l<=n)
     {
                c[k]=a[l];
                k++;
                l++;
     }
    i=st;
     while(i<=n)
     {
                a[i]=c[i];
                i++;
     }
}

void mergesort(int *a,int u,int l)
{
     if(u<l)
     {
     int i=(u+l)/2;
   
     mergesort(a,u,i-1);
     mergesort(a,i,l);
     merge(a,u,i+1,l);
     }
}

 int main()
{
      int a[50];
     
      FILE *f=fopen("hinput.txt","r");
      char c[5];
      int i=0;
      while(fscanf(f,"%s",c)!=EOF)
                                  a[i++]=atoi(c);
      int n=i-1;
      for(;i>=0;i--)
      printf("a[%d]=%d\n",i,a[i]);

      mergesort(a,0,n);


      for(i=0;i<=n;i++)
      printf("c[%d]=%d\n",i,c[i]);
   
         
      fclose(f);
      getch();
      return 0;
}

No comments:

Post a Comment

Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.