数组实现二路归并排序

使用数组实现二路归并排序

#include
#include
#include
#include
#include
#include
using namespace std;

void merge(vector&arr,int left1,int right1,int left2,int right2){
    int i=left1,j=left2;
    vectorres;
    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&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(){
   vectorarr;
   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<

你可能感兴趣的:(数组实现二路归并排序)