【板子】归并排序

#include<bits/stdc++.h>
using namespace std;

const int N = 1e6+6;



void Mergesort(int l,int r);



int main()
{
    freopen("working.in","r",stdin);
    freopen("working.out","w",stdout);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    Mergesort(1,n);
    for(int i=1;i<=n;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;
}

//Function Implementation
int n,a[N],b[N],cnt;
void Mergesort(int l,int r)
{
    if(l>=r) return ;
    int mid=(l+r)>>1;
    Mergesort(l,mid);
    Mergesort(mid+1,r);
    int i=l,j=mid+1,k=l;
    while(i<=mid && j<=r)
    {
        if(a[i]<=a[j]) b[k++]=a[i++];
        else b[k++]=a[j++],cnt+=mid-i+1;
    }  
    while(i<=mid) b[k++]=a[i++];
    while(j<=r) b[k++]=a[j++];
    for(int i=l;i<=r;i++) a[i]=b[i];
}
posted @ 2024-01-26 21:02  yeyou26  阅读(37)  评论(0编辑  收藏  举报