Inverse Count Of An Array[Microsoft,Flipkart,Amazon]

Problem:How far (or close) the array is from being sorted. If array is already sorted then inversion count is 0.
If array is sorted in reverse order that inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

Link

#include <stdio.h>

int main() {
	//code
	int t,n,cnt,i,j;
	int arr[100];
	scanf("%d",&t);
	while(t--)
	{
	    scanf("%d",&n);
	    for(i=0;i<n;i++)
	    {
	        scanf("%d",&arr[i]);
	    }
	    cnt=0;
	    for( i=0;i<n;i++)
	    {
	        for( j=i+1;j<n;j++)
	        {
	           if(arr[i]>arr[j])
	           cnt+=1;
	        }
	    }
	    printf("%d\n",cnt);
	}
	return 0;
}

 

Comments are closed.