Last active
October 6, 2021 05:44
-
-
Save misterpoloy/c2f7e2f6998502452e81c975bc6710fe to your computer and use it in GitHub Desktop.
Divide and Conquer count inversions of an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Explanation https://www.youtube.com/watch?v=owZhw-A0yWE | |
#include <vector> | |
#include <iostream> | |
using namespace std; | |
int inv_count = 0; // NAIV, since I didn't want to modify my inital merge sort impelemntation LOL | |
vector<int> merge(vector<int> left, vector<int> right) { | |
vector<int> sortedArray(left.size() + right.size(), 0); | |
int i = 0; /* i is index for left subarray*/ | |
int j = 0; /* j is index for right subarray*/ | |
int k = 0; /* k is index for resultant merged subarray*/ | |
while (i < left.size() && j < right.size()) { | |
if (left[i] <= right[j]) { | |
sortedArray[k++] = left[i++]; | |
} else { | |
sortedArray[k++] = right[j++]; | |
// This is were the magic happens, left.size() - i since you have to include all the possibilites. | |
inv_count = inv_count + ((int)left.size() - i); | |
} | |
} | |
cout << inv_count << endl; | |
while (i < left.size()) sortedArray[k++] = left[i++]; | |
while (j < right.size()) sortedArray[k++] = right[j++]; | |
return sortedArray; | |
} | |
vector<int> mergeSort(vector<int> array) { | |
if (array.size() <= 1) return array; | |
int n = (int)array.size(); | |
int mid = n / 2; | |
vector<int> left(array.begin(), array.begin() + mid); | |
vector<int> right(array.begin() + mid, array.end()); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
int countInversions(vector<int> arr) { | |
return 0; | |
} | |
int main() { | |
vector<int> arr = { 1, 20, 6, 4, 5 }; | |
mergeSort(arr); | |
cout << "number of inversions: " << inv_count << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment