//归并排序->先使子序列有序,再使子序列段间有序
//时间复杂度都是nlogn 空间复杂度是O(n)
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int>& nums){
for(auto a: nums){
cout<<a<<" ";
}
cout<<endl;
}
//nums:待排序数组,temp:用于排序的临时数组,begin:排序区间的首元素位置,end:排序区间尾元素位置
void mergeSortCore(vector<int>& nums,vector<int>& temp,int begin,int end){
if(begin>=end) return;
int mid=begin+(end-begin)/2;//计算排序区间中间位置
int start1=begin,end1=mid;//左区间
int start2=mid+1,end2=end;//右区间
mergeSortCore(nums,temp,start1,end1);//对左区间排序
mergeSortCore(nums,temp,start2,end2);//对右区间排序
int index=begin;//temp数组下标位置
//把左右已经排序好的子数组合并
while(start1<=end1&&start2<=end2){
temp[index++]=nums[start1]>nums[start2]? nums[start2++]:nums[start1++];
}
//右边子数组合并完,追加合并左数组
while(start1<=end1){
temp[index++]=nums[start1++];
}
//左边子数组合并完,追加合并右数组
while(start2<=end2){
temp[index++]=nums[start2++];
}
//将临时数组中的值复制到原数组*****
for(index=begin;index<=end;index++){
nums[index]=temp[index];
}
}
void mergeSort(vector<int>&nums){
vector<int> temp(nums);
mergeSortCore(nums,temp,0,nums.size()-1);///一定注意减一,因为是左闭右闭区间
}
int main(){
vector<int> nums{1,24,67,23,4,78,90,456};
mergeSort(nums);
print(nums);
return 0;
}
归并排序(C++版)
最新推荐文章于 2022-04-15 14:25:06 发布