I implemented the inversion count algorithm using the merge sort approach for this question.
The question begins with a number t = number of test cases and then for each test case you input size of array and then the array entries.
For each test case we have to find the number of inversions = number of shifts made by insertion sort algorithm.
I was surprised to see that only 2 test case passed out of 13 and rest all time out. Can somebody suggest a way I should go about speeding up my code?
Kindly ignore the OOP principles for the time being.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class So {
private static BufferedReader br;
private static int n,index,t,noi=0;
private static int []arr;
private static int []ans;
public static void main(String[] args)throws IOException {
int i,k=1;int s,st,j;
br=new BufferedReader(new InputStreamReader(System.in));
String []str;
t=Integer.parseInt(br.readLine());
ans=new int[t];
for(i=0;i<t;++i)
{
noi=0;
n=Integer.parseInt(br.readLine());
arr=new int[n];
str=br.readLine().split(" ");
for(k=0;k<n;++k)
arr[k]=Integer.parseInt(str[k]);
ms(0,n-1);
ans[i]=noi;
}
for(int e:ans)
System.out.println(e);
}
public static void ms(int l,int r)
{
if(r-l>0)
{
int mid=(l+r)/2;
ms(0,mid);
ms(mid+1,r);
merge(l,r);
}
}
public static void merge(int l,int r)
{
int []arr2=new int[r-l+1];
int j,k,mid=(l+r)/2;
k=mid+1;int i=0;
j=l;
while(j<=mid&&k<=r)
{
if(arr[j]<=arr[k])
arr2[i++]=arr[j++];
else {arr2[i++]=arr[k++];noi+=mid-j+1;}
}
System.arraycopy(arr,j,arr2,i,mid-j+1);
System.arraycopy(arr,k,arr2,i,r-k+1);
System.arraycopy(arr2,0,arr,l,r-l+1);
}
}