前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >归并排序求逆序数

归并排序求逆序数

作者头像
AngelNH
发布2020-04-16 15:45:20
4080
发布2020-04-16 15:45:20
举报
文章被收录于专栏:AngelNIAngelNI

君子终日乾乾,夕惕若厉,无咎。

归并排序求逆序数

练习题

poj1804

poj2299

HDU4911

代码语言:javascript
复制
/*归并排序求逆序数*/
/*我们知道mergesort是稳定排序,所以就可以根据这个特点来求序列的逆序数
在Merge()中,合并两个已经有序的数组A,B.因为A.B有序,所以,A,B各自的逆序数是0,所以AB的逆序数等于A,B之间的逆序数.
*/
#include<iostream>
using namespace std;

typedef long long ll;
const ll N = 1e7+10;
ll a[N];
ll sum;
void merge(ll *A,ll start,ll mid, ll end)
{
    ll p = start,q = mid+1;
    ll arr[end-start+1],k=0;
    while(p<=mid&&q<=end)
    {
        if(a[p]<a[q])
        {
            arr[k++] = a[p++];
        }
        else
        {
            sum+=(mid-p+1);//求逆序数
            arr[k++] = a[q++];
        } 
    }
    while(p<=mid) arr[k++] = a[p++];
    while(q<=end) arr[k++] = a[q++];
    for(ll i =start;i<=end;++i)
        a[i] = arr[i-start];
}
void mergesort(ll *A,ll start,ll end)
{
    if(start<end)
    {
        //二分;分治
        ll mid = (start+end)>>1;
        mergesort(A,start,mid);
        mergesort(A,mid+1,end);
        merge(A,start,mid,end);
    }
}
int main()
{
    ll n;
    cout<<"please input the number of data"<<endl;
    while(cin>>n&&n)
    {
        sum = 0;
        cout<<"please input the sequence"<<endl;
        for(int i =0;i<n;++i)
            cin>>a[i];
        mergesort(a,0,n-1);
        cout<<"After sorting:"<<endl;
        for(int i =0;i<n;++i)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
        cout<<"The number is"<<endl;
        cout<<sum<<endl;
        cout<<"please input the number of data"<<endl;
    }   
    system("pause");
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-03|,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 归并排序求逆序数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档