Hi GuyZ,
Merge sort is an efficient sorting algorithm which have a complexity of O(n log n). The merge sort algorithm sorts an array by spliting it into two equally sized subarrays, and sort the subarrays to merge them into sorted larger arrays until the full array is sorted.
Merge sort is an efficient sorting algorithm which have a complexity of O(n log n). The merge sort algorithm sorts an array by spliting it into two equally sized subarrays, and sort the subarrays to merge them into sorted larger arrays until the full array is sorted.
Solution
#include <iostream> using namespace std; /* Merge Sort in C++/CPP Coded By Ajith Kp (C) http://www.terminalcoders.blogspot.com */ class merge { int a[1024], sort[1024], n, i, j, tmp, k; public: void read(){ cout<<"Enter limit: "; cin>>n; cout<<"Enter "<<n<<" items: "; for(i=0;i<n;i++){ cin>>a[i]; } divide(0, n-1); } void divide(int beg, int end){ if((end-beg)>=1){ int mid = (beg+end)/2; divide(beg, mid); divide(mid+1, end); arrange(beg, mid, end); } } void arrange(int beg, int mid, int end){ i=k=beg; j=mid+1; while(i<=mid && j<=end){ if(a[i]<a[j]){ sort[k++]=a[i++]; } else{ sort[k++]=a[j++]; } } while(i<=mid){ sort[k++]=a[i++]; } while(j<=end){ sort[k++]=a[j++]; } for(i=beg;i<=end;i++){ a[i]=sort[i]; } } void show(){ cout<<"Sorted List: "; for(i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<endl; } }; int main(){ merge m; m.read(); m.show(); return 0; }