归并排序
思路
利用二分思想,划分左右区间,并让左右区间排序完成后,进行合并
# include <cstdio>
# include <iostream>
# include <algorithm>
using namespace std;
# define MX 100005
/**************************/
int cparr[MX];
/// 归并排序
void mergesort(int arr[], int l, int r) {
if (l==r) return;
int mid = (l+r)/2;
mergesort(arr, l, mid);
mergesort(arr, mid+1, r);
// 左右数组已排序完成,合并
int index = l;
int tl = l, tr = mid+1;
while(tl <= mid && tr <= r) {
if (arr[tl] <= arr[tr]) cparr[index++] = arr[tl++];
else cparr[index++] = arr[tr++];
}
while(tl<=mid) cparr[index++] = arr[tl++]; // 处理掉某一个数组没处理完的
while(tr<=r) cparr[index++] = arr[tr++];
for (int i=l; i<=r; i++) arr[i] = cparr[i]; // 拷贝回原数组
}
int main() {
int nums[6] = {5, 1, 1, 2, 0, 0};
// stable_sort(nums, nums+6);
mergesort(nums, 0, 5);
for (int i=0; i<6; i++){
printf("%d ", nums[i]);
}
}