Inversion Count

import java.util.*;
public class Main {

static long solve(long[] A, int n, int l, int r) {

	if(l >= r) return 0;

	int mid = l + (r - l)/2;
	long x = solve(A, n, l, mid);
	long y = solve(A, n, mid+1, r);
	long cnt = crossInversion(A, l, mid, r) + x + y;
	//int cnt = countCrossInversion(A, l, mid, r) + x + y;
	return cnt;
}

static long crossInversion(long[] A, int l, int mid, int r) {

	long cnt = 0;
	int i=l, j=mid+1, k=0;
	long[] arr = new long[r-l+1];
	while(i <= mid && j <= r) {
		if(A[i] <= A[j]){
			arr[k++] = A[i++];
		}else {

			cnt += mid - i + 1;
			arr[k++] = A[j++];
		}
	}
	while(i <= mid) {
		arr[k++] = A[i++];
	}
	while(j <= r) {
		arr[k++] = A[j++];
	}
	for(i=0; i<arr.length; i++) {
		A[i+l] = arr[i]; 
	}
	return cnt;
}

public static void main(String args[]) {

	Scanner sc = new Scanner(System.in);
	int t = sc.nextInt();
	while (t-- > 0) {
		int n = sc.nextInt();
		long[] A = new long[n];
		for (int i = 0; i < n; i++) {
			A[i] = Long.valueOf(sc.next());
		}
		
		System.out.println(solve(A, n, 0, n-1));
		/*for (int i = 0; i < n; i++) {
			System.out.print(A[i]+" "); 
		}
		System.out.println();
		*/
		
	}
}

}

hi @arishhaq_ae3b72621f2b5e46
updated https://ide.codingblocks.com/s/675608

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.