Merge Sort :

<br />#include<iostream>
#include<conio.h>
using namespace std;
void merge(int *,int,int,int);
void merge_sort(int *arr,int beg, int last)
{
int mid;
if(beg < last)
{
mid = (beg+last)/2;
merge_sort(arr,beg,mid);
merge_sort(arr,mid+1,last);
merge(arr,beg,mid,last);
}
return;
}
void merge(int *arr,int beg, int mid, int last)
{
int i=beg, j=mid+1,ind=beg,temp[10],k;
while((i <= mid) && ( j<= last))
{
if(arr[i] < arr[j])
{
temp[ind]=arr[i];
ind++;
i++;
}
else
{
temp[ind]=arr[j];
j++;
ind++;
}
}
while(j<=last)
{
temp[ind]=arr[j];
j++;ind++;
}
while(i<=mid)
{
temp[ind]=arr[i];
i++;
ind++;
}
for(k=beg;k<ind;k++)
{
arr[k]=temp[k];
}
}

int main()
{
int arr[10],i,n;
cout<<"Enter the size of the array: "<<endl;
cin>>n;
cout<<"Enter the elements of the array:"<<endl;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<endl<<"Unsorted Array is :"<<endl;
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
merge_sort(arr,0,n-1);
cout<<endl<<"The sorted array is:"<<endl;
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
getch();
}

Output :-

Merge sort

Leave a comment