/*******************************************/ /*******PROGRAM TO PERFORM MERGE SORT*****/ /***************************************** **/
#include < stdio.h> #include < conio.h> #define SIZE 5 void merge_sort(int [],int,int); void merge_sort_subarray(int [],int,int,int,int);
void main() { int a[SIZE],i; clrscr();
printf("\nEnter the elements of array a:\n"); for(i=0;i { scanf("%d",&a[i]); } merge_sort(a,0,SIZE-1); printf("\nAfter merging the elements are:\n"); for(i=0;i { printf("%4d",a[i]); } getch(); }
void merge_sort(int a[],int beg,int end) { int mid; if(beg { mid=(beg+end)/2; merge_sort(a,beg,mid); merge_sort(a,mid+1,end); merge_sort_subarray(a,beg,mid,mid+1,end); } }
void merge_sort_subarray(int a[],int lb,int le,int rb,int re) { int c[SIZE],i,na,nb,nc; na=lb; nb=rb; nc=lb; while((na<=le)&&(nb<=re)) { if(a[na] { c[nc]=a[na]; na++; } else { c[nc]=a[nb]; nb++; } nc++; } if(na>le) { while(nb<=re) { c[nc]=a[nb]; nb++; nc++; } } else { while(na<=le) { c[nc]=a[na]; na++; nc++; } } for(i=lb;i<=re;i++) { a[i]=c[i]; } }
For more algorithms Please visit http://www.Xpode.com
|