#include <iostream>
#include <vector>
using namespace std;
vector<int> tmp;
void mergeSort(vector<int>& nums, int l, int r) {
if (l >= r) return;
int mid = (l + r) / 2;
mergeSort(nums, l, mid);
mergeSort(nums, mid + 1, r);
int i = l, j = mid + 1;
int cnt = 0;
tmp.resize(r - l + 1);
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
tmp[cnt++] = nums[i++];
}
else {
tmp[cnt++] = nums[j++];
}
}
while (i <= mid) {
tmp[cnt++] = nums[i++];
}
while (j <= r) {
tmp[cnt++] = nums[j++];
}
for (int i = 0; i < r - l + 1; ++i) {
nums[l + i] = tmp[i];
}
}
//打印数组
void printarr(vector<int>& nums) {
for (auto n : nums) {
cout << n << " ";
}
cout << endl;
}
int main() {
vector<int> nums{ 5,1,1,2,0,0 };
printarr(nums);
mergeSort(nums, 0, nums.size() - 1);
printarr(nums);
return 0;
}
cpp实现归并排序
最新推荐文章于 2024-11-09 20:38:27 发布