#include <iostream>
#include <vector>
using namespace std;
/// 合并
void merge(vector<int>& nums, int l1, int r1, int l2, int r2, vector<int>& tmp) {
int left = l1, right = r2;
int k = l1;
while(l1<=r1 && l2<=r2) {
while (nums[l1] < nums[l2] && l1 <= r1) {
tmp[k++] = nums[l1++];
}
while (nums[l1] >= nums[l2] && l2 <= r2) {
tmp[k++] = nums[l2++];
}
}
while (l1 <= r1) {
tmp[k++] = nums[l1++];
}
while (l2 <= r2) {
tmp[k++] = nums[l2++];
}
for (int i=left; i<= right; ++i) {
nums[i] = tmp[i];
}
}
/// 拆分
void mergesort(vector<int>& nums, int l, int r, vector<int>& tmp) {
if (l == r) {
return ;
}
mergesort(nums, l, (l+r)/2, tmp);
mergesort(nums, (l+r)/2+1, r, tmp);
merge(nums, l, (l+r)/2, (l+r)/2+1, r, tmp);
}
/// 归并入口
void mergesort(vector<int>& nums) {
int n = nums.size();
if (n < 2) {
return ;
}
vector<int> tmp(n);
mergesort(nums, 0, n-1, tmp);
}
int main()
{
vector<int> nums = {2, 3, 1, 9, 7, 8, 6, 4, 5};
mergesort(nums);
for (auto &ele : nums) {
cout << ele << endl;
}
return 0;
}
标签:tmp,mergesort,归并,nums,int,C++,vector,l1,排序
From: https://www.cnblogs.com/xiaohaigegede/p/17687512.html