-
Notifications
You must be signed in to change notification settings - Fork 3
/
Problem-3.java
111 lines (83 loc) · 2.25 KB
/
Problem-3.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* @author AkashGoyal
* @date 28/05/2021
*/
/**
--------------------- Problem----------->> Count Inversion / How far the array is from being Sorted
Problem Link :- https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1
Hint:- Use Merge-Sort
[Write merge sort code and then include counter to increase count by [left_array_length - current_position_of_left_array] whenever right array element is smaller then any left array element]
Reference:- https://www.youtube.com/watch?v=kQ1mJlwW-c0
*/
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)
{
long count=0;
count=sort(arr,0,N-1);
return count;
}
static long sort(long arr[],long first, long last)
{
long count=0;
if((first<last))
{
long mid=first+(last-first)/2;
count+=sort(arr,first,mid);
count+=sort(arr,mid+1,last);
count+=merge(arr,first,mid,last);
}
return count;
}
static long merge(long arr[],long first, long mid, long last)
{
long count=0;
int n1=(int)mid-(int)first+1;
int n2=(int)last-(int)mid;
long left[]=new long[n1];
long right[]=new long[n2];
for(int i=0;i<n1;i++)
{
left[i]=arr[(int)first+i];
}
for(int i=0;i<n2;i++)
{
right[i]=arr[(int)mid+1+i];
}
int i=0;
int j=0;
int k=(int)first;
while(i<(int)n1 && j<(int)n2)
{
if(left[i]<=right[j])
{
arr[k]=left[i];
i++;
k++;
}
else
{
arr[k]=right[j];
count+=n1-i;
j++;
k++;
}
}
while(i<(int)n1)
{
arr[k]=left[i];
i++;
k++;
}
while(j<(int)n2)
{
arr[k]=right[j];
j++;
k++;
}
return count;
}
}