C++语言-外部排序算法-二路归并排序

二路归并排序,时间复杂度O(nlogn)

#include 
#include 
using namespace std;

vector<int> b(1000, 0);

void Merge(vector<int>& a, int low, int mid, int high) {
    for (int i = low; i <= high; ++i) {
        b[i] = a[i];
    }
    int t = low;
    int i = low;
    int j = mid+1;
    while (i <= mid && j <= high) {
        if (b[i] <= b[j]) {
            a[t++] = b[i++];
        } else {
            a[t++] = b[j++];
        }
    }
    while (i <= mid) {
        a[t++] = b[i++];
    }
    while (j <= high) {
        a[t++] = b[j++];
    }
}

void MergeSort(vector<int>& a, int low, int high) {
    if (low < high) {
        int mid = (low + high) / 2;
        MergeSort(a, low, mid);
        MergeSort(a, mid+1, high);
        Merge(a, low, mid, high);
    }
}

int main(int argc, char* argv[]) {
    vector<int> vec = {2, 1, 5, 3, 5, 4, 12, 11, 8, 10};
    for (int i = 0; i < vec.size(); ++i) {
        cout << vec[i] << " ";
    }
    cout << endl;
    MergeSort(vec, 0, vec.size()-1);
    for (int i = 0; i < vec.size(); ++i) {
        cout << vec[i] << " ";
    }
    cout << endl;
    return 0;
}

你可能感兴趣的:(数据结构和算法,排序算法,c++,算法)