//@1 -- first divide array a into 2 //@2 -- judge array pairs and put the smallest element after array a comparison into array d //@3 -- after the comparison between the two groups, judge the conditions //@4 -- when the rest is on the left, it means that the starting limit on the right has exceeded the range. Then, cycle to copy the remaining array directly to the d array //@5 -- when the rest is on the right, it means that the start limit on the left has exceeded the range, then cycle to copy the remaining array directly to the d array The above explains the idea of Merger algorithm Here's a detailed idea for implementing the MergerSort function Suppose you have a bunch of arrays: 8 4 5 7 1 3 6 2 In fact, this algorithm is similar to a binary tree, which is decomposed as follows 8 4 5 7 1 3 6 2 8 4 5 7 1 3 6 2 8 4 5 7 1 3 6 2 4 8 5 7 1 3 6 / / / merger 4 5 7 8 1 2 3 6 1 2 3 4 5 6 7 8 The following is the implementation of the code:
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; template<class Type> ///For example: 5 25 55 10 20 30 //@1 -- first divide array a into 2 //@2 -- judge array pairs and put the smallest element after array a comparison into array d //@3 -- after the comparison between the two groups, judge the conditions //@4 -- when the rest is on the left, it means that the starting limit on the right has exceeded the range. Then, cycle to copy the remaining array directly to the d array //@5 -- when the rest is on the right, it means that the start limit on the left has exceeded the range, then cycle to copy the remaining array directly to the d array void Merger(Type a[],Type d[],int left,int mid,int right)///Merge two ordered arrays (also called merge sort) { int i=left,j=mid+1,k=left; while((i<=mid)&&(j<=right) )///To ensure that the boundary between two sides can be compared within a certain range { if(a[i]<=a[j]) d[k++]=a[i++]; else d[k++]=a[j++]; } if(i>mid)///When the limit on the left is out of range, the array on the right is left; { for(int p=j;p<=right;p++) d[k++]=a[p]; } else { for(int p=i;p<=mid;p++) d[k++]=a[p]; } } template<class Type> void MergerSort(Type a[],int left,int right) { int d[right]; if(left<right)///There are at least two points { int i=(left+right)/2; MergerSort(a, left,i);///Divide and rule (divide and rule) divide left constantly MergerSort(a,i+1,right);///On the right ////When there is only one number left on both sides Merger(a,d,left,i,right); for(int p=left;p<=right;p++) a[p]=d[p];///Copy back to array a (because I'm going to output array a at the end) } } int main() { int a[]={1,21,12,36,67,99,56,100,99}; int b[9]; MergerSort(a,0,8); for(int i=0;i<9;i++) cout<<a[i]<<" "; return 0; }
The operation results are as follows: