-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_8.cpp
More file actions
68 lines (68 loc) · 1.85 KB
/
question_8.cpp
File metadata and controls
68 lines (68 loc) · 1.85 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
/*
Consider an array ofA[1,2,3,...,n] be an array ofndistinct num-bers. Ifi < jandA[i]> A[j], then we call the the pair (i,j) as an
inversion ofA. For example, the five inversions in the arrayA:<2,3,8,6,1>are (1,5),(2,5),(3,4),(3,5),(4,5).
Given anarray of numbers, design the pseudocode and the correspondingcode that follows ‘Divide-Conquer-Combine’ strategy for
com-puting the number of inversions in the array and analyse thesame.
*/
#include <iostream>
#include <vector>
using namespace std;
long long mergeAndCountInversions(vector<int>& arr, vector<int>& temp, int left, int mid,
int right) {
int i = left;
int j = mid + 1;
int k = left;
long long inversions = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k] = arr[i];
i++;
} else {
temp[k] = arr[j];
inversions += mid - i + 1;
j++;
}
k++;
}
while (i <= mid) {
temp[k] = arr[i];
i++;
k++;
}
while (j <= right) {
temp[k] = arr[j];
j++;
k++;
}
for (int idx = left; idx <= right; idx++) {
arr[idx] = temp[idx];
}
return inversions;
}
long long mergeSortAndCountInversions(vector<int>& arr, vector<int>& temp, int left, int
right) {
long long inversions = 0;
if (left < right) {
int mid = left + (right - left) / 2;
inversions += mergeSortAndCountInversions(arr, temp, left, mid);
inversions += mergeSortAndCountInversions(arr, temp, mid + 1, right);
inversions += mergeAndCountInversions(arr, temp, left, mid, right);
}
return inversions;
}
long long countInversions(vector<int>& arr) {
int size = arr.size();
vector<int> temp(size);
return mergeSortAndCountInversions(arr, temp, 0, size - 1);
}
int main() {
vector<int> arr = {2, 3, 8, 6, 1};
cout << "Original array: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
long long inversions = countInversions(arr);
cout << "Number of inversions: " << inversions << endl;
return 0;
}