歸併排序

代碼:

#include <iostream>
#include<vector>

using namespace std;

void merge_two_arr(vector<int> &a,int l1,int h1,int l2,int h2)
{
    int index1=l1;
    int index2=l2;
    vector<int> temp;
    while(index1<=h1&&index2<=h2)
    {
        if(a[index1]<=a[index2])
            temp.push_back(a[index1++]);
        else
            temp.push_back(a[index2++]);
    }

    while(index1<=h1)
        temp.push_back(a[index1++]);
    while(index2<=h2)
        temp.push_back(a[index2++]);

    int i=0;
    for(int j=l1;j<=h1;j++)
        a[j]=temp[i++];
    for(int k=l2;k<=h2;k++)
        a[k]=temp[i++];
}

void part(vector<int> &a,int low,int high)
{
    if(low<high)
    {
         int middle=(low+high)>>1;
         part(a,low,middle);
         part(a,middle+1,high);
         merge_two_arr(a,low,middle,middle+1,high);
    }
}

int main()
{
    vector<int> a={2,3,0,1,2,4,5,6,9};
    part(a,0,a.size()-1);
    for(auto i:a)
    cout << i << endl;
    return 0;
}

輸出:

0
1
2
2
3
4
5
6
9

Process returned 0 (0x0)   execution time : 0.077 s
Press any key to continue.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章