//写法1:for循环写法 //[low...mid]和[mid+1...high]各自有序 将两个部分归并 voidmerge(int A[], int n, int low, int mid, int high){//需要传入数组大小n以节省不必要的空间浪费 int i, j, k; int *B = (int *)malloc(n * sizeof(int));//辅助数组B for (k = low; k <= high; ++k) B[k] = A[k]; for (i = low, j = mid + 1, k = i; i <= mid && j <= high; ++k) {//核心归并操作 if (B[i] <= B[j]) A[k] = B[i++]; else A[k] = B[j++]; } while(i <= mid) A[k++] = B[i++];//未归并完的部分直接复制到尾部 while(j <= high) A[k++] = B[j++]; }
voidmergeSort(int A[], int n, int low, int high){ if (low < high) { int mid = (low + high)/2;//从中间划分 mergeSort(A, n, low, mid);//左半部分归并排序 mergeSort(A, n, mid + 1, high);//右半部分归并排序 merge(A, n, low, mid, high);//归并操作 } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//写法2:while循环写法 voidmerge_sort(int arrA[], int low, int high){ if (low >= high) return; int mid = (low + high) / 2; merge_sort(arrA, low, mid); merge_sort(arrA, mid + 1, high); int i = low, j = mid + 1, k = 0; while (i <= mid && j <= high) { if (arrA[i] <= arrA[j]) arrB[k++] = arrA[i++]; else arrB[k++] = arrA[j++]; } while (i <= mid) arrB[k++] = arrA[i++]; while (j <= high) arrB[k++] = arrA[j++]; for (i = low, j = 0; i <= high; i++, j++) arrA[i] = arrB[j];//将数组数据拷贝回arrA }