-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum_swaps_2.cpp
42 lines (31 loc) · 925 Bytes
/
minimum_swaps_2.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
#define value int
#define index int
// Complete the minimumSwaps function below.
int minimumSwaps(vector<int> arr) {
int swaps = 0;
std::vector<std::pair<value , index>> pairs;
for(size_t i = 0 ; i < arr.size() ; i += 1 ){
pairs.push_back(
std::pair<value,index>{ arr[i],i }
);
}
// sort pairs by values
std::sort(pairs.begin() , pairs.end() ,
[&](
std::pair<value,index> const& a ,
std::pair<value,index> const& b
) -> bool {
return a.first < b.first;
}
);
// resort and count swaps
for(size_t i = 0 ; i < pairs.size() ; i += 1){
if( pairs[i].second == i) continue;
else {
std::swap(pairs[i], pairs[ pairs[i].second ]);
swaps += 1;
i-=1;
}
}
return swaps;
}