Skip to content

Commit

Permalink
Add sorting question having graph approach
Browse files Browse the repository at this point in the history
  • Loading branch information
nandwalritik committed May 11, 2021
1 parent 0abb391 commit b16c702
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions graph/minSwapstoSort.cpp
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;
}

0 comments on commit b16c702

Please sign in to comment.