-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_minSwapsToSort.cpp
58 lines (54 loc) · 1.3 KB
/
GFG_minSwapsToSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Minimum Swaps to Sort
https://practice.geeksforgeeks.org/problems/minimum-swaps/1
*/
class Solution
{
public:
//Function to find the minimum number of swaps required to sort the array.
int minSwaps(vector<int>&nums)
{
vector<pair<int,int>> x;
int n = nums.size();
for(int i=0; i<n; i++)
x.push_back({nums[i], i});
sort(x.begin(), x.end());
//int swaps=0;
//for(int i=0; i<n; i++)
//{
// int j=x[i].second;
// //if(i==j)
// // continue;
// //else
// int cyclesize=0;
// while(i!=j)
// {
// cyclesize++;
// swap(x[i], x[j]);
// j = x[i].second;
// }
// if(cyclesize>0)
// swaps += cyclesize;
//}
////for(int i=0; i<n; i++) cout<<x[i].first<<" "<<x[i].second<<") ";
//return swaps;
int swaps=0;
vector<bool> vis(n, 0);
for(int i=0; i<n; i++)
{
int j=x[i].second;
if(vis[i] || j == i) continue;
int cyclesize=0;
j=i;
while(!vis[j])
{
cyclesize++;
vis[j]=true;
j = x[j].second;
}
swaps += cyclesize-1;
}
//for(int i=0; i<n; i++) cout<<x[i].first<<" "<<x[i].second<<") ";
return swaps;
}
};