归并排序

逆序数

 
#include <stdio.h>
const int M = 1000001;
int num[M], temp[M], n;
double back;
void merg(int left, int m, int right) 
{
 int i, j, p;
 i = left, j = m + 1, p = 0;
 while ( i <= m && j <= right ) 
 {
  if ( num[j] < num[i] ) 
  {
   temp[p++] = num[j++];
   back += m - i + 1;
   }
  else temp[p++] = num[i++];
  }
 while ( i <= m ) temp[p++] = num[i++];
 while ( j <= right ) temp[p++] = num[j++];
 for ( i = 0, j = left; i < p; i++, j++ )
  num[j] = temp[i];
 }

void mergesort(int left, int right) 
{
 int m = ( left + right ) / 2;
 if ( left < right ) 
 {
  mergesort(left, m);
  mergesort(m+1, right);
  merg(left, m, right);
  }
 }

int main () 
{
 int i,m;
 scanf("%d",&m);
 while ( m--)
 {
	 scanf("%d", &n);
  for ( i = 0; i < n; i++ )
   scanf("%d", &num[i]);
   back = 0;
  mergesort(0, n-1);
  printf("%.0lf\n", back);
  }
 return 0;
 }        


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