#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int n;
void main()
{
int i,low,high;
int a[5];
void mergesort(int a[5],int low,int high);
void display(int a[5]);
clrscr();
cout<<"Merge Sort\n";
cout<<"Enter the length of list";
cin>>n;
cout<<"Enter list Elements";
for(i=0;i<n;i++)
{
cin>>a[i];
}
low=0;
high=n-1;
mergesort(a,low,high);
display(a);
getch();
}
//This function is to split the list into sublists
void mergesort(int a[5],int low,int high)
{
int mid;
void combine(int a[5],int low,int mid,int high);
if(low<high)
{
mid=(low+high)/2;//split the list at mid
mergesort(a,low,mid);//first sublist
mergesort(a,mid+1,high);
combine(a,low,mid,high);
}
}
//This function is to for merging the two sublists
void combine(int a[5],int low,int mid,int high)
{
int i,j,k;
int temp[5];
k=low;
i=low;
j=mid+1;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
temp[k]=a[i];
i++;
k++;
}
while(j<=high)
{
temp[k]=a[j];
j++;
k++;
}
//copy the elements from temp array to a
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}
//Function to display sorted array
void display(int a[5])
{
int i;
cout<<"The Sorted array is";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
}
#include<conio.h>
#include<stdlib.h>
int n;
void main()
{
int i,low,high;
int a[5];
void mergesort(int a[5],int low,int high);
void display(int a[5]);
clrscr();
cout<<"Merge Sort\n";
cout<<"Enter the length of list";
cin>>n;
cout<<"Enter list Elements";
for(i=0;i<n;i++)
{
cin>>a[i];
}
low=0;
high=n-1;
mergesort(a,low,high);
display(a);
getch();
}
//This function is to split the list into sublists
void mergesort(int a[5],int low,int high)
{
int mid;
void combine(int a[5],int low,int mid,int high);
if(low<high)
{
mid=(low+high)/2;//split the list at mid
mergesort(a,low,mid);//first sublist
mergesort(a,mid+1,high);
combine(a,low,mid,high);
}
}
//This function is to for merging the two sublists
void combine(int a[5],int low,int mid,int high)
{
int i,j,k;
int temp[5];
k=low;
i=low;
j=mid+1;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
temp[k]=a[i];
i++;
k++;
}
while(j<=high)
{
temp[k]=a[j];
j++;
k++;
}
//copy the elements from temp array to a
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}
//Function to display sorted array
void display(int a[5])
{
int i;
cout<<"The Sorted array is";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
}