POJ2299(归并排序)

#include <stdio.h>
#include <stdlib.h>
__int64 counter;
void merge(long int A[],int p,int q,int r)
{
	int n1,n2,i,k,j,m=1,n=1;
	long int *L,*R;
	n1=q-p+1;
	n2=r-q;
	L=malloc((n1+2)*sizeof(int));
	R=malloc((n2+2)*sizeof(int));
	for (i=p;i<=q;i++)
		L[m++]=A[i];
	for (i=q+1;i<=r;i++)
		R[n++]=A[i];
	i=1;j=1;
	for (k=p;k<=r;k++)
	{
		if ( (L[i]<=R[j] && i<=n1) || j>n2)
		{
			A[k]=L[i];
			i++;
		}
		else
		{
			A[k]=R[j];
			counter+=n1-i+1;
			j++;
		}
	}
	free(L);
	free(R);
}

void mergesort(long int A[],int p,int r)
{
	int q;
	if (p<r)
	{
		q=(p+r)/2;
		mergesort(A,p,q);
		mergesort(A,q+1,r);
		merge(A,p,q,r);
	}
}

int main()
{
	long int A[500000];
	int i,size,p=1;
	while (1)
	{
		counter=0;
		scanf("%d",&size);
		if (size==0)
			break;
	  for (i=1;i<=size;i++)
		  scanf("%ld",&A[i]);
	  mergesort(A,p,size);
    printf("%I64d\n",counter);
	}
	return 0;
}

你可能感兴趣的:(POJ2299(归并排序))