The two ordered series combined into an ordered series, which we call " merge ."
Merge sort (Merge Sort) is to use the idea of merging the number of columns to sort. According to a particular implementation, merge sort including " top-down " and " bottom-up " in two ways.
1. From the bottom up merge sort : to be sorted columns divided into a number of length sub-number of columns, and these columns twenty-two combined; obtained several one ordered sequence 2, then the number of columns twenty-two They were combined; to obtain a plurality of ordered sequence length of 4, then they were combined twenty-two; incorporated directly up into a number of columns. This was the sort of result we want. (Refer to picture below)
2. From top to bottom merge sort : it and "bottom-up" in the opposite direction of the sort. It basically comprises three steps:
① Decomposition - The current interval is divided into two, i.e., seeking split point = MID (High + Low) / 2;
② Solving - recursively two subintervals a [low ... mid] and a [mid + 1 ... high] for merge sort. Recursive termination condition is the length of a sub-interval.
③ combined - is_sorted two subintervals a [low ... mid] and a [mid + 1 ... high] as an ordered merge interval a [low ... high].
Merge sort down from the implementation code:
1 //归并排序 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <string> 6 #include <cmath> 7 #include <algorithm> 8 using namespace std; 9 void Merge(int a[],int start,int mid,int end) 10 { 11 int *temp=new int[end-start+1]; 12 int i=start; 13 int j=mid+1; 14 int k=0; 15 while(i<=mid&&j<=end) 16 { 17 if(a[i]<=a[j]) temp[k++]=a[i++]; 18 else temp[k++]=a[j++]; 19 } 20 while(i<=mid) temp[k++]=a[i++]; 21 while(j<=end) temp[k++]=a[j++]; 22 for(i=0;i<k;i++) a[start+i]=temp[i]; 23 delete[] temp; 24 } 25 void MergeSort_Down(int a[],int start,int end) 26 { 27 if(a==NULL||start>=end) return; 28 int mid=(start+end)/2; 29 MergeSort_Down(a,start,mid); 30 MergeSort_Down(a,mid+1,end); 31 Merge(a,start,mid,end); 32 } 33 int main() 34 { 35 int a[]={999,888,333,221,345,990,899}; 36 int ilen=sizeof(a)/sizeof(a[0]); 37 cout<<"排序前:"<<endl; 38 for(int i=0;i<ilen;i++)cout<<a[i]<<" "; 39 cout<<endl; 40 MergeSort_Down(a,0,ilen-1); 41 cout<<"排序后:"<<endl; 42 for(int i=0;i<ilen;i++) cout<<a[i]<<" "; 43 cout<<endl; 44 return 0; 45 }
Reference: https://www.cnblogs.com/skywang12345/p/3602369.html