归并算法模板

//归并
#include 
#include 

typedef long long ll;
using namespace std;

const ll maxn = 1e5 + 7;

ll c = 0;
ll a[maxn],b[maxn];
void mergesort(ll *a,ll *b,ll l,ll r)
{
    if(l >= r)return ;
    ll mid = (l + r) / 2;
    ll p = l,q = mid + 1, i = l;
    mergesort(a,b,p,mid);
    mergesort(a,b,mid + 1,r);
    while(p <= mid || q <= r)
    {
        if(q > r || (p <= mid && a[p] <= a[q]))
        {
            b[i++] = a[p++];
        }
        else
        {
            b[i++] = a[q++];
            c += mid - p + 1;
        }
    }
    for(int i = l; i <= r; i ++)
    {
        a[i] = b[i];
    }
}

int main()
{
    ll n;
    cout << "请你输输入你想要排序的表的长度" << endl;
    cin >> n;
    cout << "请输入表中的元素" << endl;
    for(int i = 1; i <= n; i ++)
    {
        cin >> a[i];
    }

    mergesort(a,b,1,n);

    cout << "表中的元素按照从小到大排列如下" << endl;
    for(int i = 1; i <= n; i ++)
    {
        cout << a[i] << " ";
        if(i % 10 == 0)cout << endl;
    }
    cout << endl;

    return 0;
}

 

你可能感兴趣的:(知识点,归并排序,模板)