A blog to help students to learn programming in various languages including C, C++, Java, Python and many more.

Subscribe For Free Latest Updates!

We'll not spam mate! We promise.

Saturday 23 January 2016



Program Screenshot
Output

#include <iostream>
using namespace std;
int mergeSort(int a[],int beg,int end);
int merge(int a[],int beg,int mid,int end);
int main()
{
int n,a[100];
cout<<"Enter no. of values: ";
cin>>n;
cout<<"Enter "<<n<<" values: ";
for(int x=0;x<n;x++) {
cin>>a[x];
}
mergeSort(a,0,n-1);
cout<<"Array after Sorting using Merge Sort:\n";
for(int x=0;x<n;x++) {
cout<<a[x]<<"\n";
}
return(0);
}
int mergeSort(int a[],int beg,int end)
{
if(end <= beg) {
return(0);
}
int mid=(beg+end)/2;
mergeSort(a,beg,mid);
mergeSort(a,mid+1,end);
merge(a,beg,mid,end);
}
int merge(int a[],int beg,int mid,int end)
{
int h=beg,i=beg,j=mid+1;
int b[100];
while(h<=mid && j<=end) {
if(a[h]<=a[j]) {
b[i]=a[h];
i++;
h++;
} else {
b[i]=a[j];
i++;
j++;
}
}
if(h>mid) {
for(int k=j;k<=end;k++) {
b[i]=a[k];
i++;
}
} else {
for(int k=h;k<=mid;k++) {
b[i]=a[k];
i++;
}
}
for(int k=beg;k<=end;k++) {
a[k]=b[k];
}
}


0 comments :

Post a Comment



Copyright © 2016 - ProgrmIt - All Rights Reserved
(Articles Cannot Be Reproduced Without Author Permission.)
Design By : | Powered By: Blogger