归并排序c语言
1 void mergeAdd(int arr[], int left, int mid, int right, int *temp){
2 int i = left; 3 int j = mid + 1; 4 int k = left;//临时下标 5 while (i <= mid&&j <= right){ 6 if (arr[i] < arr[j]){ 7 temp[k++] = arr[i++]; 8 } 9 else{ 10 temp[k++] = arr[j++]; 11 } 12 } 13 while (i <= mid){ 14 temp[k++] = arr[i++]; 15 } 16 while (j <= right){ 17 temp[k++] = arr[j++]; 18 } 22 memcpy(arr + left, temp + left, sizeof(int)*(right - left+1)); 23 } 24 void mergeSort(int arr[],int left,int right,int *temp){ 25 int mid = 0; 26 if (left < right){ //归并排序采用先分再并的思想,效率上为O(nlgn), 空间上为O(n),需要耗用多一倍的空间 27 mid = left + (right - left) / 2; 28 mergeSort(arr, left, mid, temp); 29 mergeSort(arr, mid + 1, right, temp); 30 mergeAdd(arr, left, mid, right, temp); 31 }
32 }
是时候好好总结下自己走过的路。