cpp
复制代码
#include<iostream>
using namespace std;
void Merge(int* arr,int left,int right,int mid, int*& tmparr)
{
int begin1 = left, end1 = mid;
int begin2 = mid + 1, end2 = right;
int tmpi = left;
//下面合并两个数组为一个有序数组(升序);
while (begin1<=end1&&begin2<=end2)
{
if (arr[begin1] < arr[begin2])
{
tmparr[tmpi++] = arr[begin1++];
}
else if (arr[begin1] >= arr[begin2])
{
tmparr[tmpi++] = arr[begin2++];
}
}
while (begin1<=end1)
{
tmparr[tmpi++] = arr[begin1++];
}
while (begin2 <= end2)
{
tmparr[tmpi++] = arr[begin2++];
}
//每次子数组排序好都必须拷贝到原数组,使原数组越来越接近有序。如果被分割的子数组都不有序,那么合并成的大数组也一定不会有序。
memcpy(arr+left, tmparr+left, sizeof(int)*(right-left+1));
}
//时间复杂度O(N*logN),空间复杂度O(N);
void Merge_Sort(int* arr,int left,int right,int*& tmparr)
{
if (left >= right) return;
int mid = (left + right) / 2;
Merge_Sort(arr,left,mid,tmparr);
Merge_Sort(arr, mid+1, right,tmparr);
Merge(arr,left,right,mid,tmparr);
}
int main()
{
int arr[] = {66,72,53,41,38,39,25,40,90};
int size = sizeof(arr) / sizeof(int);
int* tmparr = new int[size];
//构建一个一模一样一样的数组,这也就是空间复杂度O(N)的原因;
Merge_Sort(arr,0,size-1,tmparr);
delete []tmparr;
for (auto& e:arr)
{
cout<<e<<" ";
}
return 0;
}