-
Notifications
You must be signed in to change notification settings - Fork 70
/
inversion_count.cpp
78 lines (72 loc) · 1.39 KB
/
inversion_count.cpp
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
#include <bits/stdc++.h>
using namespace std;
int merge(int arr[], int low, int mid, int high)
{
int i = low, j = mid + 1, k = low;
int b[high];
int count=0;
while (i <= mid && j <= high)
{
if (arr[i] <= arr[j])
{
b[k] = arr[i];
i++;
k++;
}
else
{
b[k] = arr[j];
j++;
k++;
count+=mid+1-i;
}
}
if (i > mid)
{
while (j<=high)
{
b[k]=arr[j];
j++;
k++;
}
}
else{
while (i<=mid)
{
b[k]=arr[i];
i++;
k++;
}
}
for(k=low;k<=high;k++)
arr[k]=b[k];
return count;
}
int mergesort(int arr[], int low, int high)
{
int mid;
int count = 0;
if (high > low)
{
mid = (high + low) / 2;
count += mergesort(arr, low, mid);
count += mergesort(arr, mid + 1, high);
count += merge(arr, low, mid, high);
}
return count;
}
int main()
{
int n;
cout << "enter array length=";
cin >> n;
int arr[n];
cout << "\n enter array to be sorted=";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << mergesort(arr, 0, n);
cout << endl;
return 0;
}