-
Notifications
You must be signed in to change notification settings - Fork 57
/
assignment2.cpp
68 lines (64 loc) · 1.58 KB
/
assignment2.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
#include <bits/stdc++.h>
using namespace std;
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
unsigned int merge(int arr[], int temp[], int l, int m, int r) {
unsigned int inversions = 0;
int i = l;
int j = m;
int k = l;
while (i < m && j <= r) {
if (arr[i] <= arr[j]) {
temp[k] = arr[i];
i++;
} else {
temp[k] = arr[j];
j++;
inversions += m-i;
}
k++;
}
while (i < m) {
temp[k] = arr[i];
i++;
k++;
}
while (j <= r) {
temp[k] = arr[j];
j++;
k++;
}
for (int i = l; i <= r; i++) {
arr[i] = temp[i];
}
return inversions;
}
unsigned int count(int arr[], int temp[], int l, int r) {
unsigned int inversions = 0;
if (r > l) {
int m = (r+l)/2;
inversions = count(arr, temp, l, m);
inversions += count(arr, temp, m+1, r);
inversions += merge(arr, temp, l, m+1, r);
}
return inversions;
}
int main() {
int arr_size = 100000;
int arr[arr_size];
ifstream file("IntegerArray.txt");
string str;
int i = 0;
while (getline(file, str)) {
arr[i] = stoi(str);
i++;
}
// int arr[] = { 1, 20, 6, 4, 5 };
// int arr_size = sizeof(arr) / sizeof(arr[0]);
int temp[arr_size];
/* mergeSort(arr, 0, arr_size-1);
for (int i = 0; i < arr_size; i++) {
cout << arr[i] << " ";
} */
cout << count(arr, temp, 0, arr_size-1) << endl;
}