欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++归并排序

程序员文章站 2022-03-03 18:40:19
...

C++归并排序

​
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 m = 0; m < tmp.size(); m++)
        data[start+m] = tmp[m];  // 注意
}

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

​