归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法,归并排序对序列的元素进行逐层折半分组,然后从最小分组开始比较排序,合并成一个大的分组,逐层进行,最终所有的元素都是有序的。
void _MergeSort(int* a, int left, int right, int* tmp) { //递归终止条件 if (left >= right) { return; } int mid = (left + right) / 2; //[left, mid] mid [mid+1, right] 有序 _MergeSort(a, left, mid, tmp); _MergeSort(a, mid + 1, right, tmp); int begin1 = left, end1 = mid; int begin2 = mid + 1, end2 = right; int i = left; while (begin1 <= end1 && begin2 <= end2) { if (a[begin1] <= a[begin2]) { tmp[i++] = a[begin1++]; } else { tmp[i++] = a[begin2++]; } } //如果[begin1,end1]区间没有结束 while (begin1<=end1) { tmp[i++] = a[begin1++]; } //如果[begin2,end2]区间没有结束 while (begin2 <= end2) { tmp[i++] = a[begin2++]; } //tmp 数组的值拷贝回a for (int j = left; j <= right; ++j) { a[j++] = tmp[j]; } } //归并排序 void MergeSort(int* a, int n) { int* tmp = (int*)malloc(sizeof(int) * n); if (tmp == NULL) { printf("malloc failed!\n"); exit(-1); } _MergeSort(a, 0, n - 1, tmp); free(tmp); tmp = NULL; }