求字符串逆序对的数目

没什么好说的,采用分治法,算法复杂度O(nlgn),帖个代码先

 

// project1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<string.h>

#define LENGTH 100

//合并
//str[beg..mid]和str[mid+1..end]已有序
//现str[beg..end]合并成有序,使用辅助数组assist
int merge(char* str,char* assist,int beg,int mid,int end){
    int reverseNum=0;
    int i=beg,j=mid+1,k=beg;
    while(i<=mid && j<=end){
        if(str[i]>str[j]){//如果逆序
            reverseNum += mid-i+1;
            assist[k++]=str[j++];
        }
        else assist[k++]=str[i++];
    }
    while(i<=mid)
        assist[k++]=str[i++];
    
    while(j<=end)
        assist[k++]=str[j++];
    //将排好序的数组重新复制到原数组
    for(int l=beg;l<k;l++)
        str[l]=assist[l];
    return reverseNum;
}
 
//计算逆序数
//归并分治法,对str进行归并排序
//使用一个辅助数组
int reverse_num(char *str,char* assist,int beg,int end){
    int reverseNum=0;
    if(end>beg){
        int mid=(end+beg)/2;
        reverseNum+=reverse_num(str,assist,beg,mid);
        reverseNum+=reverse_num(str,assist,mid+1,end);
        reverseNum+=merge(str,assist,beg,mid,end);
    }
    return reverseNum;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char str[LENGTH]="1357924680";
    char tmp[LENGTH];
    memset(tmp,0,sizeof(char)*LENGTH);
    printf("%d\n",reverse_num(str,tmp,0,strlen(str)-1));
    return 0;
}



 

 

 

 

posted @ 2013-11-20 14:07  IT_cnblogs  阅读(640)  评论(0编辑  收藏  举报