1.归并排序
1 void merge(int *arr, int start, int mid, int end) 2 { 3 int i = start; 4 int j = mid + 1; 5 int k = 0; 6 int len = end - start + 1; 7 int *temp = new int[len]; 8 9 while(i <= mid && j <= end) 10 { 11 if(arr[i] < arr[j]) 12 { 13 temp[k] = arr[i]; 14 k++; 15 i++; 16 } 17 else 18 { 19 temp[k] = arr[j]; 20 k++; 21 j++; 22 } 23 } 24 25 while(i <= mid) 26 { 27 temp[k] = arr[i]; 28 k++; 29 i++; 30 } 31 32 while(j <= end) 33 { 34 temp[k] = arr[j]; 35 k++; 36 j++; 37 } 38 39 for(k = 0; k < len; k++) 40 { 41 arr[start + k] = temp[k]; 42 } 43 } 44 45 void _mergeSort(int *arr, int start, int end) 46 { 47 if(start == end) 48 { 49 return; 50 } 51 52 int mid = (start + end ) / 2; 53 _mergeSort(arr, start, mid); 54 _mergeSort(arr, mid + 1, end); 55 merge(arr, start, mid, end); 56 } 57 58 void mergeSort(int *arr, int n) 59 { 60 _mergeSort(arr, 0, n - 1); 61 }