C++ 归并排序算法实现

c++归并排序函数实现如下:

void merge_sort(vector<int> &data, int start, int end) {
    if (start < end) {
        int mid = (start + end) / 2;
        merge_sort(data, start, mid);
        merge_sort(data, mid + 1, end);
        merge(data, start, mid, end);
    }
}

void merge(vector<int> &data, int start, int mid, int end) {
    vector<int> tmp;
    int i = start, j = mid + 1;
    while (i != mid + 1 && j != end + 1) {
        if (data[i] <= data[j]) {
            tmp.push_back(data[i++]);
        } else {
            tmp.push_back(data[j++]);
        }
    }
    while (i != mid + 1) {
        tmp.push_back(data[i++]);
    }
    while (j != end + 1) {
        tmp.push_back(data[j++]);
    }
    for (int i = 0; i < tmp.size(); i++) {
        data[start + i] = tmp[i];
    }
}

完整代码如下(包含main函数,头文件,测试数组):

#include <iostream>
#include <vector>
using namespace std;

//函数声明
void merge_sort(vector<int> &data, int start, int end);
void merge(vector<int> &data, int start, int mid, int end);
void output_array(vector<int> &data);   //输出

void merge_sort(vector<int> &data, int start, int end) {
    if (start < end) {
        int mid = (start + end) / 2;
        merge_sort(data, start, mid);
        merge_sort(data, mid + 1, end);
        merge(data, start, mid, end);
    }
}

void merge(vector<int> &data, int start, int mid, int end) {
    vector<int> tmp;
    int i = start, j = mid + 1;
    while (i != mid + 1 && j != end + 1) {
        if (data[i] <= data[j]) {
            tmp.push_back(data[i++]);
        } else {
            tmp.push_back(data[j++]);
        }
    }
    while (i != mid + 1) {
        tmp.push_back(data[i++]);
    }
    while (j != end + 1) {
        tmp.push_back(data[j++]);
    }
    for (int i = 0; i < tmp.size(); i++) {
        data[start + i] = tmp[i];
    }
}

void output_array(vector<int> &data) {
    for(auto i : data) {
        cout << i << " ";
    }
    cout << endl;
}

int main() {
    int _data[] = {2, 4, 6, 0, 9, 8};
    vector<int> data(_data, _data + 6);
    merge_sort(data, 0, (int)data.size() - 1);
    output_array(data);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值