Company: Myntra, Microsoft, Flipkart, BankBazaar, Amazon, Adobe
Given an array, find inversion count of array.
Inversion Count for an array indicates – 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).
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).
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
Output:
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
Output:
Print the inversion count of array.
Constraints:
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ C ≤ 500
Example:
1 ≤ N ≤ 100
1 ≤ C ≤ 500
Example:
Input:
1
5
2 4 1 3 5
1
5
2 4 1 3 5
Output:
3
3
CODE:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int m=sc.nextInt();
for(int mi=0;mi<m;mi++){
int n=sc.nextInt();
int [] ar= new int[n];
for(int i=0;i<n;i++){
ar[i]=sc.nextInt();
}
System.out.println(getInversionCount(ar));
}
}
public static int getInversionCount(int array[]) {
int length = array.length;
int count = 0;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
count++;
}
}
}
return count;
}
}
EXECUTION TIME:0.19s
Comments
Post a Comment