使用数组实现二路归并排序
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<list>
#include<queue>
using namespace std;
void merge(vector<int>&arr,int left1,int right1,int left2,int right2){
int i=left1,j=left2;
vector<int>res;
while(i<=right1&&j<=right2){
if(arr[i]<=arr[j]){
res.push_back(arr[i]);
i++;
}
else{
res.push_back(arr[j]);
j++;
}
}
while(i<=right1){
res.push_back(arr[i]);
i++;
}
while(j<=right2){
res.push_back(arr[j]);
j++;
}
j=0;
for(i=left1;i<=right2;i++){
arr[i]=res[j++];
}
return;
}
void merge_sort(vector<int>&arr,int left,int right){
if(left>=right)
return;
merge_sort(arr,left,left+(right-left)/2);
merge_sort(arr,left+(right-left)/2+1,right);
merge(arr,left,left+(right-left)/2,left+(right-left)/2+1,right);
return;
}
int main(){
vector<int>arr;
int n;
cin>>n;
while(n--){
int tmp;
cin>>tmp;
arr.push_back(tmp);
}
merge_sort(arr,0,arr.size()-1);
for(int tmp:arr){
cout<<tmp<<" ";
}
}