You are on page 1of 2

//WAP to demonstrate mergesort.

#include<iostream.h> #define MAX 20 void mergesort(int a[],int ,int); //to divide array void merge(int a[],int,int,int); // to merge array int main(void) { int i,n,a[MAX]; cout<<"\nEnter size of array: "; cin>>n; if(n>MAX) cout<<"\nArray out of bounds"; else { cout<<"\nEnter elements of array: "; for(i=0;i<n;i++) cin>>a[i]; mergesort(a,0,n-1); cout<<"\nSorted array is: "; for(i=0;i<n;i++) cout<<' '<<a[i]; } return 0; } void mergesort(int a[],int beg,int end) { int mid; if(beg<end)

{ mid=(beg+end)/2; mergesort(a,beg,mid); mergesort(a,mid+1,end); merge(a,beg,mid,end); } } void merge(int a[MAX],int lb,int mid,int ub) { int h=lb,j=mid+1,i=lb,temp[MAX]; // lb is lower bound & ub is upper // bound of array while((h<=mid)&&(j<=ub)) { if(a[h]<a[j]) temp[i]=a[h++]; else temp[i]=a[j++]; i++; } if(h>mid) { while(j<=ub) temp[i++]=a[j++]; } else { while(h<=mid) temp[i++]=a[h++]; } for(int k=lb;k<=ub;k++) a[k]=temp[k]; }

You might also like