递归实现就是树的后序遍历
void mergeSort_recursive(vector<int> &arr, int start, int end)
{if (start >&#61; end){return;}int mid &#61; start &#43; ((end - start) >> 1);mergeSort_recursive(arr, start, mid);mergeSort_recursive(arr, mid &#43; 1, end);int len &#61; end - start &#43; 1;vector<int> tmp(len);int idx &#61; 0;for (int i &#61; start, j &#61; mid &#43; 1; i <&#61; mid || j <&#61; end;){int left &#61; i <&#61; mid ? arr[i] : INT_MAX;int right &#61; j <&#61; end ? arr[j] : INT_MAX;if (left <&#61; right){tmp[idx&#43;&#43;] &#61; arr[i&#43;&#43;];}else {tmp[idx&#43;&#43;] &#61; arr[j&#43;&#43;];}}for (int i &#61; 0; i < len; i&#43;&#43;){arr[start &#43; i] &#61; tmp[i];}
}
迭代实现思路&#xff1a;先合并长度为1的数组&#xff0c;然后在合并长度为2、4、8的数组。
归并排序的迭代实现不推荐使用像快速排序那样直接使用栈模拟递归&#xff0c;后序遍历会麻烦很多&#xff01;
void merge_sort(int arr[], int len)
{int *a &#61; arr;int *b &#61; (int *)malloc(len * sizeof(int));int seg, start;for (seg &#61; 1; seg < len; seg &#43;&#61; seg) {for (start &#61; 0; start < len; start &#43;&#61; seg &#43; seg){int low &#61; start, mid &#61; min(start &#43; seg, len), high &#61; min(start &#43; seg &#43; seg, len);int k &#61; low; int start1 &#61; low, end1 &#61; mid;int start2 &#61; mid, end2 &#61; high;while(start1 < end1 || start2 < end2){int left &#61; start1<end1?a[start1]:INT_MAX;int right &#61; start2<end2?a[start2]:INT_MAX;if(left <&#61;right){b[k&#43;&#43;]&#61;a[start1&#43;&#43;];}else{b[k&#43;&#43;]&#61;a[start2&#43;&#43;];}}}int *temp &#61; a;a &#61; b;b &#61; temp;}if (a !&#61; arr) {int i;for (i &#61; 0; i < len; i&#43;&#43;)b[i] &#61; a[i]; b &#61; a; }free(b);
}