1 #include<iostream> 2 #define MAX 5000003 3 #define SENTINEL 2000000000 4 using namespace std; 5 6 int L[MAX / 2 + 2], R[MAX / 2 + 2]; 7 int cnt; 8 9 void merge (int A[], int left, int mid, int right) //合并 right为数组长 10 { 11 int n1 = mid - left; 12 int n2 = right - mid; 13 for( int i = 0; i < n1; i++ ) L[i] = A[left + i]; 14 for( int i = 0; i < n2; i++ ) R[i] = A[mid + i]; 15 L[n1] = R[n2] = SENTINEL; //分到最小时L、R中各有一个数,若进行比较合并,需比较两次,才能合并入A,故需要一个 很大的sentinel ; 16 int i = 0, j = 0; 17 for(int k = left; k < right; k++) 18 { 19 cnt++; 20 if( L[i] <= R[j]) 21 A[k] = L[i++]; 22 else 23 A[k] = R[j++]; 24 } 25 26 } 27 28 void mergeSort( int A[], int left, int right) 29 { 30 if( left + 1 < right) 31 { 32 int mid = (left + right) / 2; 33 mergeSort(A, left, mid); 34 mergeSort(A, mid, right); 35 merge(A, left, mid,right); 36 } 37 } 38 39 int main() 40 { 41 int A[MAX], n, i; 42 43 cin >> n; 44 for( i = 0; i < n; i++) cin >> A[i]; 45 46 mergeSort(A, 0, n); 47 48 for( i = 0;i < n;i++ ) 49 { 50 if( i ) cout << " "; 51 cout << A[i]; 52 } 53 cout << endl; 54 55 return 0; 56 }