CLRS2.4__逆序对

#include<iostream>
using namespace std;


int main(int argc,char* argv[])
{
	int Merge_Count(int*,int,int);
	int merge(int*,int,int,int);

	int A[]={2,3,8,6,1};

	cout<<Merge_Count(A,0,4)<<endl;;

	system("pause");
	return 0;
}

int Merge(int* A,int p,int q,int r)
{
	int n1=q-p;
	int n2=r-q;
	int i,j;

	int *L=new int[n1+1]();
	int* R=new int[n2+1]();

	for(i=0;i<n1;i++)
		L[i]=A[p+i];
	for(i=0;i<n2;i++)
		R[i]=A[q+i+1];

	L[n1]=INT_MAX;
	R[n2]=INT_MAX;

	i=0;j=0;
	int inversion=0;
	bool counted=false;
	for(int k=p;k<=r;k++)
	{
		if(counted==false && L[i]>R[j])
		{
			inversion+=n1-i+1;
			counted=true;
		}
		if(L[i]<R[j])
			i++;
		else
		{
			j++;
			counted=false;
		}
	}
	delete []L;
	delete []R;

	return inversion;
}

int Merge_Count(int* A,int p,int r)
{
	int count=0;
	if(p<r)
	{
		int q=(p+r)/2;
		int l1=Merge_Count(A,p,q);
		int l2=Merge_Count(A,q+1,r);
		count=l1+l2+Merge(A,p,q,r);
	}
	return count;
}

  

posted on 2012-05-28 14:35  紫金树下  阅读(119)  评论(0编辑  收藏  举报