#include <iostream> using namespace std; void merge(int a[],int lb,int mid,int ub) { int b[ub+1]; int i=lb; int j=mid+1; int k=lb; while(i<=mid && j<=ub) { if(a[i]<a[j]) { b[k]=a[i]; i++; } else if(a[j]<a[i]) { b[k]=a[j]; j++; } k++; } if(i>mid) { while(j<=ub) { b[k]=a[j]; i++;j++; } } else if(j>ub) { while(i<=mid) { b[k]=a[i]; i++;k++; } } for(int k=0;k<=ub;k++) { a[i]=b[k]; } } void mergesort(int a[],int lb,int ub) { if(lb<ub) { int mid=(lb+ub)/2; mergesort( a,lb, mid); mergesort( a, mid+1,ub); merge( a,lb,mid, ub); } } int main() { int a[100]; int n; cout<<"Enter the no. of element"; cin>>n; cout<<"Enter the element"; for(int i=0;i<n;i++) { cin>>a[i]; } int b[100]; int ub=n-1; int lb=0; mergesort(a,lb,ub); cout<<"Array after sorting"<<endl; for(int i=0;i<n;i++) { cout<<a[i]; cout<<" "; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter