Recursive method
#include <iostream>using namespace std;void Merge (int r[],int r1[],int b,int m,int e) {int i=b;int j=m+1;int K=b;whil E ((i<=m) && (j<=e)) {if (R[i]<=r[j]) {r1[k]=r[i];i++;k++;} else{r1[k]=r[j];j++;k++;}} if ((I<=m)) {while (i<=m) {r1[k++]=r[i++];}} else if (j<=e) {while (j<=e) {r1[k++]=r[j++];}}} void mergesort (int r[],int r1[],int s,int t) {int r2[100];if (s==t) {r1[s]=r[s];} Else{int m= (s+t)/2; MergeSort (R,R2,S,M); MergeSort (r,r2,m+1,t); Merge (r2,r1,s,m,t);}} void Main () {int a[7]={8,7,9,3,4,1,2}; MergeSort (a,a,0,6);//Recursive call allows you to update the A value for (int i=0;i<7;i++) {cout<<a[i]<< ';} System ("Pause");}
Non-recursive method
#include <iostream>using namespace std;void merge (int r[],int r1[],int b,int m,int e) {//one-time merge int i=b,j=m+1,k=b; while ((i<=m) && (j<=e)) {if (R[i]>=r[j]) {r1[k++]=r[i++];} Else{r1[k++]=r[j++];}} if (i<=m) {while (i<=m) r1[k++]=r[i++];} else if (j<=e) {while (j<=e) r1[k++]=r[j++];}} void Mergepass (int r[],int r1[],int n,int h) {//a trip sort int i=0;while (i<=n-2*h) {Merge (r,r1,i,i+h-1,i+2*h-1); i=i+2*h;} if (i<n-h) {Merge (r,r1,i,i+h-1,n-1);} else{for (int s=i;s<n;s++) {r1[s]=r[s];}}} void mergesort (int r[],int r1[],int n) {int h=1;while (h<n) {mergepass (r,r1,n,h); h=h*2;for (int i=0;i<n;i++) {r[i]= r1[i];//Update Sequence value}}}void main () {int a[7]={8,7,9,4,1,2,3};int b[7];//non-recursive mergesort (a,b,7); for (int i=0;i<7;i++) {cout <<b[i]<< ';} System ("Pause");}
Summary of sorting algorithm (II.) Merger method