归并排序采用分治策略,
分解:将待排序的n个元素的序列成各具n/2个元素的两个子序列
解决:使用归并排序递归的排序两个子序列
合并:合并两个已排序的子序列,以产生已排序的答案
void mergeSort(int *arr, int size){int *temp = malloc(sizeof(int) * size);if (temp != NULL){mSort(arr, 0, size - 1, temp);free(temp);}};void mSort(int *arr, int start, int end, int *temp){if (start < end){int center = (start + end) >> 1;mSort(arr, start, center, temp);mSort(arr, center + 1, end, temp);merge(arr, start, end, center + 1, temp);}};void merge(int *arr, int leftStart, int rightEnd, int rightStart, int *temp){int leftEnd = rightStart - 1; // 两个子序列中左则序列的末尾下标int index = leftStart; // temp 起始下标int total = rightEnd - leftStart; // 两个子序中元素的个数while (leftStart <= leftEnd && center <= end){if (arr[leftStart] <= arr[rightStart]){temp[index++] = arr[leftStart++];}else{temp[index++] = arr[rightStart++];}}while (leftStart <= leftEnd){temp[index++] = arr[leftStart++];}while (rightStart <= rightEnd){temp[index++] = arr[rightStart++];}for (size_t i = 0; i <= total; i++, rightEnd--){arr[rightEnd] = temp[rightEnd];}};
