首页 > 编程语言 > 详细

归并排序

时间:2021-04-14 15:32:23      阅读:18      评论:0      收藏:0      [点我收藏+]

 

#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;
}

 

归并排序

原文:https://www.cnblogs.com/0patrick/p/14657255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!