Hello Guys! Finding all the Inversions in an array is quite a popular problem. I have implemented Merge Sort to solve the problem, it takes O(n log n) time.
The code Below in C++ lets you Print all the Inversions in an Array..So, what are you waiting for, go ahead and find all the Inversions in array of your choice.
#include<algorithm>
#include<vector>
#include<array>
using namespace std;
void merge(vector<int>& array, vector<int>& array1, vector<int>& array2) {
array.clear();
int i, j, k,l;
for( i = 0, j = 0, k = 0; i < array1.size() && j < array2.size(); k++){
if(array1.at(i) <= array2.at(j)){
array.push_back(array1.at(i));
i++;
}else if(array1.at(i) > array2.at(j)){
for(l=i;l!=array1.size();++l){
cout<<array1.at(l)<<" "<<array2.at(j)<<endl;
}
array.push_back(array2.at(j));
j++;
l=0;
}
k++;
}
while(i < array1.size()){
array.push_back(array1.at(i));
i++;
}
while(j < array2.size()){
array.push_back(array2.at(j));
j++;
}
}
void merge_sort(vector<int>& array) {
if (1 < array.size()) {
vector<int> array1(array.begin(), array.begin() + array.size() / 2);
merge_sort(array1);
vector<int> array2(array.begin() + array.size() / 2, array.end());
merge_sort(array2);
merge(array, array1, array2);
}
}
int main(){
vector<int>v = {1, 20, 6, 4, 5};
merge_sort(v);
for(int &x:v)
cout<<x<<" " ;
return 0;
}
Note: The following code sorts the input array, if you don't want to change the input array then run the code on the copy of input array.
If you need any clarifications, Please don't hesitate to poke me in the comments below. Wishing You "HAPPY INVERSIONS".
No comments:
Post a Comment