問題 B: 基礎排序III:歸併排序

題目描述

歸併排序是一個時間複雜度爲O(nlogn)的算法,對於大量數據遠遠優於冒泡排序與插入排序。

這是一道排序練習題,數據量較大,請使用歸併排序完成。

 

輸入

第一行一個數字n,代表輸入的組數

其後每組第一行輸入一個數字m,代表待排序數字的個數

其後m行每行一個數據,大小在1~100000之間,互不相等,最多有10萬個數據。

輸出

升序輸出排好序的數據,每行一個數字

樣例輸入

1
10
10
9
8
7
6
5
4
3
2
1

樣例輸出

1
2
3
4
5
6
7
8
9
10
#include<bits/stdc++.h>
using namespace std;

void Merge(vector<int>&res, int L1, int R1, int L2, int R2)
{
    vector<int>ans(R2-L1+10);
    int i = L1, j=L2, index=0;
    while(i<=R1 && j<=R2)
    {
        if(res[i]<res[j])
            ans[index++] = res[i++];
        else
            ans[index++] = res[j++];

    }
    if(i<=R1)
    {
        while(i<=R1)
            ans[index++] = res[i++];
    }
    if(j<=R2)
    {
        while(j<=R2)
            ans[index++] = res[j++];
    }
    index = 0;
    for(int i=L1; i<=R2; ++i)
        res[i] = ans[index++];
}


void mergesort(vector<int>&res, int i, int j)
{
    if(i < j)
    {
        int pos = (j-i)/2+i;
        mergesort(res, i, pos);
        mergesort(res, pos+1, j);
        Merge(res, i, pos, pos+1,j);
    }
}

int main()
{
    int n;
    cin >> n;
    while(n--)
    {
        int m;
        cin >> m;
        vector<int>res(m);
        for(int i=0; i<m; ++i)
            cin >> res[i];
        mergesort(res, 0, res.size()-1);
        for(int i=0; i<m; ++i)
        {
            cout << res[i];
            if(i==n-1)
                continue;
            else
                cout<<endl;
        }
    }

    return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章