Algorithm - merge sort (top-down, bottom-up)

top down

. 1 #include <the iostream>
 2 #include <algorithm>
 . 3 #include " InsertionSort.h " 
. 4  
. 5  the using  namespace STD;
 . 6  
. 7 Template <typename T>
 . 8  // the arr [l ... mid] and arr [mid + 1 ... r] merge two parts 
. 9  void __merge (ARR T [], int L, int MID, int R & lt) {
 10      T AUX [L-R & lt + . 1 ];
 . 11      // array to copy AUX [ ] 
12 is      for ( int I = L; I <= R & lt; I ++ )
 13 is         AUX [IL] = ARR [I];
 14      // initialization, i, j points to the left, the right half of the starting position of the index 
15      int I = L, J = MID + . 1 ;
 16      for ( int K = L; K <= R & lt; K ++ ) {
 . 17          // If the left half has been processed 
18 is          IF (I> MID) {
 . 19              ARR [K] = AUX [J- L];
 20 is              J ++ ; 
 21 is          }
 22 is          // if the right half has been processed 
23 is          the else  IF (J> R & lt) {
 24              ARR [K] = AUX [I- L];
 25             ++ I ;
 26 is          }
 27          // left half of the element pointed to <right half of the element pointed to 
28          the else  IF (AUX [IL] <AUX [J- L]) {
 29              ARR [K] = AUX [IL ];
 30              I ++ ;
 31 is          }
 32          // left half of the element pointed> = right half of the elements referred to 
33 is          the else {
 34 is              ARR [K] = AUX [J- L];
 35              J ++ ;
 36          }
 37 [      }
 38 is  }
 39  
40  // recursive merge sort, for arr [l ... r] are sorted range
41 is Template <typename T>
 42 is  void __mergeSort (T ARR [], int L, int R & lt) {
 43 is      
44 is      IF (L> = R & lt)
 45          return ; 
 46 is          
47      int MID = (L + R & lt) / 2 ;
 48      __mergeSort ( ARR, L, MID);
 49      __mergeSort (ARR, MID + . 1 , R & lt);
 50      // optimization, two front and rear portions of ordered is not merged 
51 is      IF (ARR [MID]> ARR [MID + . 1 ])
 52 is          __merge (ARR, L, MID, R & lt);     
 53 is  } 
 54 is  
55 template<typename T>
56 void mergeSort(T arr[] , int n){
57     __mergeSort( arr , 0 , n-1 );
58 }

Self-bottom improvement

1  // bottom-up merging, the list can be sorted for 
2 Template <typename T>
 . 3  void mergeSortBU (ARR T [], int n-) {
 . 4      for ( int SZ = 1 ; SZ <= n-; + SZ = SZ)
 . 5          for ( int I = 0 ; I + SZ <n-; I + = SZ + SZ)
 . 6              // for arr [i ... i + sz- 1] and arr [i + sz ... i + 2 * sz -1] for merging 
. 7              __merge (ARR, I, SZ I + - . 1 , min (SZ + SZ + I - . 1 , N- . 1 ));             
 . 8 }

Application: seeking to reverse

Guess you like

Origin www.cnblogs.com/cxc1357/p/12149129.html