-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add sorting question having graph approach
- Loading branch information
1 parent
0abb391
commit b16c702
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
#include<bits/stdc++.h> | ||
using namespace std; | ||
int minSwaps(int ar[],int n){ | ||
vector<pair<int,int>> p(n); | ||
for(int i = 0 ; i < n ; i++){ | ||
p[i].first=ar[i]; | ||
p[i].second=i; | ||
} | ||
// for(auto x:p) | ||
// cout<<x.first<<" "<<x.second<<endl; | ||
sort(p.begin(),p.end()); | ||
int ans=0; | ||
vector<bool> vis(n,false); | ||
for(int i=0;i<n;i++){ | ||
if(vis[i] || p[i].second == i) | ||
continue; | ||
int j=i; | ||
int cycle_sz = 0; | ||
while(!vis[j]){ | ||
vis[j]=true; | ||
// cout<<p[j].first<<" "; | ||
j = p[j].second; | ||
|
||
cycle_sz++; | ||
} | ||
// cout<<endl; | ||
// cout<<cycle_sz<<" "; | ||
ans+=(cycle_sz-1); | ||
} | ||
return ans; | ||
} | ||
int main(){ | ||
int ar[]={5,3,8,32,6,15}; | ||
cout<<minSwaps(ar,sizeof(ar)/sizeof(int))<<endl; | ||
return 0; | ||
} |