#include <iostream.h>

//  Count Inversions ROUTINE 

int inversions(int A[], int B[], int l, int r) {
  int i,j,bptr,mid;

  if (l == r) return 0;
  mid = (l + r)/2;
  int i1 = inversions(A,B,l,mid);
  int i2 = inversions(A,B,mid+1,r);

//   NOW MERGE THE 2 HALVES, UNTIL ONE STACK IS EMPTY
  
  int i3 = 0;
  i = bptr = l;
  j = mid+1;
  while (i <= mid && j <= r){
    if (A[i] <= A[j]) {
      B[bptr] = A[i]; i++;
    }
    else {
      B[bptr] = A[j];
      j++;
      i3 = i3 + mid -i + 1;
    }
    bptr++;
  }

 //  COPY REMAINING ELEMENTS OF OTHER STACK TO TEMP ARRAY

  while (i <= mid) {
     B[bptr] = A[i]; i++; bptr++;
     }

//   MOVE NEEDED PORTION BACK INTO A

  for (int k=l; k <= j-1; k++)
     A[k] = B[k];

  return i1+i2+i3;
}

   

