归并排序

 

#include <iostream>
#include <vector>
using namespace std;
void merge_sort(vector<int>& vec,int left, int right);

int main(){
    vector<int> input = {};
    for (int i = 0; i < 10; i++)
    {
        input.emplace_back(rand()%10);
        cout << input[i]<< " ";
    }
    cout << endl;
    merge_sort(input, 0, 9);
    for (int i = 0; i < 10; i++)
    {
        cout << input[i]<< " ";
    }
}
void merge_sort(vector<int>& vec,int left, int right){
    int mid = left + (right - left) / 2;
    if(left < right){
        merge_sort(vec, left, mid);
        merge_sort(vec, mid + 1, right);
    }
    else return;
    vector<int> store(right - left + 1);
    int l1 = left;
    int r1 = mid;
    int l2 = mid + 1;
    int r2 = right;
    int i = 0;
    while(l1 <= r1 && l2 <= r2){
        if(vec[l1] <= vec[l2]){
            store[i++] = vec[l1++];
        }
        else{
            store[i++] = vec[l2++];
        }
    }
    while(l2 <= r2){
        store[i++] = vec[l2++];
    }
    while(l1 <= r1){
        store[i++] = vec[l1++];
    }
    for(int j = 0; j <= i-1; j++){
        vec[left++] = store[j];
    }
    return;
}

 

posted @ 2021-04-14 12:12  zeroPatrick  阅读(22)  评论(0编辑  收藏  举报