逆序对

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
void print(int a[],int n)
{
    for(int i=0;i<n;i++) cout << a[i] << '\t';
    cout << endl;
}
void  mergeSort(int a[],int b[],int L,int R,int &ans)
{
    if(L==R) return ;
    int mid = (L+R)/2;
    mergeSort(a,b,L,mid,ans);
    mergeSort(a,b,mid+1,R,ans);
    int k=L,i=L,j=mid+1;
    while(i<=mid && j<=R)
    {
        if(a[i]<a[j]) b[k++]=a[i++];
        else 
        {
            b[k++]=a[j++];
            ans += mid-i+1; //逆序对 
        }
    } 
    while(i<=mid) b[k++]=a[i++];
    while(j<=R) b[k++]=a[j++];
    for(i=L;i<=R;i++) a[i]=b[i];
}
int main(void)
{
    freopen("D:\\1.txt","r",stdin);
    int n,a[100],b[100],ans=0;
    cin >> n;
    for(int i=0;i<n;i++) cin >> a[i];
    print(a,n);
    mergeSort(a,b,0,n-1,ans);
    print(a,n);
    cout << "ans=" << ans; 
    return 0;    
}

 

posted @ 2019-03-02 16:23  最美遇见你  阅读(169)  评论(0编辑  收藏  举报