forked from priyanshu003/ImportantConcepts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInversionCount.java
89 lines (77 loc) · 2.35 KB
/
InversionCount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//Initial Template for Java
import java.util.*;
import java.io.*;
import java.lang.*;
class Sorting
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while(t-- > 0)
{
long n = sc.nextLong();
long arr[] = new long[(int)n];
for(long i = 0; i < n; i++)
arr[(int)i] = sc.nextLong();
System.out.println(new Inversion_of_Array().inversionCount(arr, n));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Inversion_of_Array
{
// arr[]: Input Array
// N : Size of the Array arr[]
static long inversionCount(long arr[], long N)
{
long count=0;
long temp[]=new long[(int)N];
count=merge(arr,temp,0,N-1);
return count;
}
static long merge(long arr[],long temp[], long left, long right)
{
long mid,count=0;
if(left<right)
{
mid=(left+right)/2;
count=merge(arr,temp,left,mid);
count=count+merge(arr,temp,mid+1,right);
count=count+merge_sort(arr,temp,left,mid+1,right);
}
return count;
}
static long merge_sort(long arr[],long temp[],long left,long mid,long right)
{
long count=0;
long i=left;
long j=mid;
long k=left;
while(i<=mid-1&&j<=right)
{
if(arr[(int)i]<=arr[(int)j])
{
temp[(int)k++]=arr[(int)i++];
}
else
{
temp[(int)k++]=arr[(int)j++];
count=count+(mid-i);
}
}
while(i<=mid-1)
{
temp[(int)k++]=arr[(int)i++];
}
while(j<=right)
{
temp[(int)k++]=arr[(int)j++];
}
for( i=left;i<=right;i++)
{
arr[(int)i]=temp[(int)i];
}
return count;
}