-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArray-Count-Inversion
More file actions
130 lines (113 loc) · 2.76 KB
/
Array-Count-Inversion
File metadata and controls
130 lines (113 loc) · 2.76 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
##method 1
class Solution
{
// arr[]: Input Array
// N : Size of the Array arr[]
//Function to count inversions in the array.
static long inversionCount(long arr[], long n)
{
int inv_count = 0;
for (int i = 0; i<n-1 ; i++)
for (int j = i+1; j<n; j++)
if (arr[i] > arr[j])
inv_count++;
return inv_count;
}
}
##method 2
class Solution
{
// arr[]: Input Array
// N : Size of the Array arr[]
//Function to count inversions in the array.
static long inversionCount(long arr[], long N)
{
// Your Code Here
long[] temp= new long[arr.length];
long ans=findmerging(arr,temp,0,arr.length-1);
return ans;
}
public static long findmerging(long[] arr, long[] temp, int left, int right)
{
int mid=0;
long cnt=0;
if(right>left)
{
mid=(left+right)>>1;
cnt+=findmerging(arr,temp,left,mid);
cnt+=findmerging(arr,temp,mid+1,right);
cnt+=merge(arr,temp,left,mid+1,right);
}
return cnt;
}
public static long merge(long[] arr, long[] temp, int left, int mid, int right)
{
int i,j,k;
long cnt=0;
i=left;
j=mid;
k=left;
while((i<=mid-1) && (j<=right))
{
if(arr[i]<=arr[j])
{
temp[k++]=arr[i++];
}
else
{
temp[k++]=arr[j++];
cnt+=(mid-i);
}
}
while(i<=mid-1)
{
temp[k++]=arr[i++];
}
while(j<=right)
{
temp[k++]=arr[j++];
}
for(i=left;i<=right;i++)
{
arr[i]=temp[i];
}
return cnt;
}
}
##method 3
class Solution
{
// arr[]: Input Array
// N : Size of the Array arr[]
//Function to count inversions in the array.
static long inversionCount(long arr[], long N)
{
// ArrayList <Integer> a = new ArrayList<>();
// int x=0;
long count =0;
// while(count != 0){
for(int j=1 ; j<N;j++){
if(arr[j-1] > arr[j] ){
// System.out.println("arr[j] = "+arr[j]);
// System.out.println("arr[j-1] = "+arr[j-1]);
long temp;
count++;
// a.add(1);
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j=0;
}else{
continue;
}
}
// }
// int j=0;
// while(j<a.size()){
// x = x+a.get(j);
// j++;
// }
// Long l= new Long(i);
return count;
}
}