----MERGE SORT----
Merge Sort is a Divide and conqueror problem. It divides an input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves.It follows the top-down approach. Our Team "Programmerix" has created our own version of Merging code so that we can solve many students problem.We use recursive function and random function this code to help the programmers to insert the inputs via keyboard.Hope you all like it-----
----Program----
#include<conio.h>
#include<stdlib.h>
void Merge(int [],int,int,int);
void input(int a[],int n)
{
int i;
randomize();
for(i=0;i<n;i++)
{
a[i]=rand()%100;
}
cout<<"array is \n";
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
cout<<endl;
}
void Ms(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
Ms(a,low,mid);
Ms(a,mid+1,high);
Merge(a,low,mid,high);
}
}
void Merge(int a[],int low,int mid,int high)
{
int i,j;
i=low;
j=mid+1;
int n,m,k=low;
n=mid;
m=high;
int b[10];
for( ;i<=n&&j<=m;k++)
{
if(a[i]<a[j])
{
b[k]=a[i];
i++;
}
else
{
b[k]=a[j];
j++;
}
}
for( ;i<=n;k++)
{
b[k]=a[i];
i++;
}
for( ;j<=m;k++)
{
b[k]=a[j];
j++;
}
for(i=low;i<=high;i++)
{
a[i]=b[i];
}
}
void display(int a[],int low,int high)
{
int i;
cout<<"Sorted array is "<<endl;
for(i=low;i<=high;i++)
{
cout<<" "<<a[i];
}
}
void main()
{
int i,n,m,low,high,a[10];
clrscr();
cout<<"enter the max value for input in array 1 \n";
cin>>n;
input(a,n);
low=0;
high=n-1;
Ms(a,low,high);
display(a,low,high);
getch();
}
Example-----

Comments
Post a Comment