You are on page 1of 3

Merge sort

#include<stdio.h> #include<conio.h> #define MAX 20 void mergesort(int a[],int low,int high); void merge(int a[],int beg,int mid,int end); void display(int a[],int num); void main() { int n,i,a[MAX]; clrscr(); printf("Enter the number of elements (<MAX )\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("\nArray elements before sorting are:\n"); display(a,n); mergesort(a,0,n-1); printf("\nArray elements after sorting are:\n"); display(a,n); getch(); } void mergesort(int a[],int low,int high) { int mid; if(low<high) { mid=(low+high)/2; mergesort(a,low,mid); mergesort(a,mid+1,high); merge(a,low,mid,high); }

} void merge(int a[],int beg, int mid,int end) { int temp,b[MAX],left,right,i; left=beg; right=mid+1; temp=beg; while((left<=mid) && (right<=end)) { if(a[left]<a[right]) { b[temp]=a[left]; left=left+1; } else { b[temp]=a[right]; right=right+1; } temp=temp+1; } while(left<=mid) { b[temp]=a[left]; left=left+1; temp=temp+1; } while(right<=end) { b[temp]=a[right]; right=right+1; temp=temp+1; } for(i=beg;i<=end;i++) { a[i]=b[i]; } }

void display(int a[],int num) { int i; for(i=0;i<num;i++) printf("%d\t",a[i]); }