#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void merge(std::vector<int> &nums, int left, int mid, int right){
int i = left; // left指向第一个序列中的首元素,mid为最后一个元素
int j = mid + 1; // j指向第二个序列中的首元素
std::vector<int> tmp (right-left+1);
int k = 0; // k为tmp首位置
while(i<=mid && j<=right){
if(nums[i] <= nums[j]){
tmp[k++] = nums[i++];
}else{
tmp[k++] = nums[j++];
}
}
while(i <= mid){
tmp[k++] = nums[i++];
}
while(j <= right){
tmp[k++] = nums[j++];
}
std::copy(tmp.begin(), tmp.end(), nums.begin()+left);
}
void divide(std::vector<int> &nums, int left, int right){
if(left >= right) return;
else{
int mid = (left + right) / 2;
divide(nums, left, mid);
divide(nums, mid+1, right);
merge(nums, left, mid, right);
}
}
void mergeSort(std::vector<int> &nums){
int n = nums.size();
divide(nums, 0, n-1);
}
int main(){
std::vector<int> nums {49, 38, 65, 97, 76, 13, 27, 49, 0, 14, -6, 900};
mergeSort(nums);
std::copy(nums.begin(), nums.end(), std::ostream_iterator<int>{std::cout, ", "});
}
归并排序 C++实现
于 2023-09-11 10:57:07 首次发布