逆序对问题的另一种经典解法:归并排序

逆序对问题:
在树状数组的应用中已经对逆序对问题进行了一次解答。
下面说明另一种经典解法:归并排序

#include <iostream>
#include <stdio.h>
using namespace std;

int num[1005];
int temp[1005];
int ans;

int merge_sort(int s, int e)
{
    if(s == e) // 返回
        return 0;
    int m = (s+e)>>1;  // 右移一位,相当于除2
//cout<<m;
    //getchar();
    merge_sort(s,m);
    merge_sort(m+1,e);

    int cnt = 0;
    int i,j;
    for( i = s, j = m+1; i<=m && j <= e; )
    {
        if( num[i] > num[j] )
        {
             temp[cnt++] = num[j];
             j++;
            ans +=  (m-i+1); //更新逆序对的数量
        }
        else
        {
            temp[cnt++] = num[i];
            i++;
        }
    }
    while( i<= m)
    {
        temp[cnt++] = num[i++];
    }
    while(j<= e)
        temp[cnt++] = num[j++];

    for(int c = 0; c<cnt ; c++)
        num[s+c] = temp[c];      //重新幅值回来,得到有序的数组
}
int main(int arg, char** argv)
{
    int n_num;
    cout<<"输入数字的个数:";
    cin>>n_num;
    if(n_num<1)
    {
        cout<< "wrong input !";
        return -1;
    }
    ans = 0;
    cout<< "请输入"<<n_num<<"个数:";
    for(int i = 1 ; i<= n_num ; i++)
    {
        cin>>num[i];
    }
    merge_sort(1,n_num);
    for(int i = 1; i<=n_num; i++)
        cout<< num[i]<<" ";
    cout<<endl<< "逆序对的数量:"<<ans;
    return 0;
}


做了一个搬运工,手打的代码,加深映像!!!
TJU-26E
2016-5-30

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值