Created
August 6, 2020 19:09
-
-
Save Divay9Sharma/5d2314904b1661cdeacd2e3401247bd8 to your computer and use it in GitHub Desktop.
Min swap required to sort the 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
| long countInversions(vector<int> arr) { | |
| map<int,pair<int,int>> mp; | |
| int count; | |
| for(int i=0;i<arr.size();i++){ | |
| mp[arr[i]].first++; | |
| } | |
| count = mp.size(); | |
| mp.insert({0,{0,0}}); | |
| for(auto i=mp.begin();i!=mp.end();i++){ | |
| if(count>0){ | |
| count--; | |
| next(i,1)->second.second = next(i,1)->second.first + i->second.second; | |
| } | |
| } | |
| for(int i=0;i<arr.size();i++){ | |
| count = arr[i]; | |
| arr[i] = mp[arr[i]].second - mp[arr[i]].first; | |
| mp[count].first = mp[count].first- 1; | |
| } | |
| int ans =0; | |
| int j,temp; | |
| for(int i=0;i<arr.size();i++){ | |
| if(arr[i]!=-1){ | |
| count=0; | |
| j = arr[i]; | |
| while(j!=i){ | |
| count++; | |
| temp = arr[j]; | |
| arr[j] = -1; | |
| j = temp; | |
| } | |
| ans += count; | |
| } | |
| } | |
| return ans; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment