Summary of sorting algorithm (II.) Merger method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.