归并排序采用分治策略,
    分解:将待排序的n个元素的序列成各具n/2个元素的两个子序列
    解决:使用归并排序递归的排序两个子序列
    合并:合并两个已排序的子序列,以产生已排序的答案

    1. void mergeSort(int *arr, int size)
    2. {
    3. int *temp = malloc(sizeof(int) * size);
    4. if (temp != NULL)
    5. {
    6. mSort(arr, 0, size - 1, temp);
    7. free(temp);
    8. }
    9. };
    10. void mSort(int *arr, int start, int end, int *temp)
    11. {
    12. if (start < end)
    13. {
    14. int center = (start + end) >> 1;
    15. mSort(arr, start, center, temp);
    16. mSort(arr, center + 1, end, temp);
    17. merge(arr, start, end, center + 1, temp);
    18. }
    19. };
    20. void merge(int *arr, int leftStart, int rightEnd, int rightStart, int *temp)
    21. {
    22. int leftEnd = rightStart - 1; // 两个子序列中左则序列的末尾下标
    23. int index = leftStart; // temp 起始下标
    24. int total = rightEnd - leftStart; // 两个子序中元素的个数
    25. while (leftStart <= leftEnd && center <= end)
    26. {
    27. if (arr[leftStart] <= arr[rightStart])
    28. {
    29. temp[index++] = arr[leftStart++];
    30. }
    31. else
    32. {
    33. temp[index++] = arr[rightStart++];
    34. }
    35. }
    36. while (leftStart <= leftEnd)
    37. {
    38. temp[index++] = arr[leftStart++];
    39. }
    40. while (rightStart <= rightEnd)
    41. {
    42. temp[index++] = arr[rightStart++];
    43. }
    44. for (size_t i = 0; i <= total; i++, rightEnd--)
    45. {
    46. arr[rightEnd] = temp[rightEnd];
    47. }
    48. };