Skip to content

Commit eaf2ebd

Browse files
SwapSort.cpp (TheAlgorithms#754)
* Create Swap Sort(Minimum) * Update Swap Sort(Minimum) * Update Swap Sort(Minimum) * Rename Swap Sort(Minimum) to SwapSort.cpp * Update SwapSort.cpp * Update SwapSort.cpp * Update SwapSort.cpp * Rename SwapSort.cpp to swap_sort.cpp Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 52f46c5 commit eaf2ebd

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

sorting/swap_sort.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// C++ program to find minimum number of swaps required to sort an array
2+
#include <algorithm>
3+
#include <iostream>
4+
#include <utility>
5+
#include <vector>
6+
7+
// Function returns the minimum number of swaps
8+
// required to sort the array
9+
int minSwaps(int arr[], int n) {
10+
// Create an array of pairs where first
11+
// element is array element and second element
12+
// is position of first element
13+
std::pair<int, int> arrPos[n];
14+
for (int i = 0; i < n; i++) {
15+
arrPos[i].first = arr[i];
16+
arrPos[i].second = i;
17+
}
18+
19+
// Sort the array by array element values to
20+
// get right position of every element as second
21+
// element of pair.
22+
std::sort(arrPos, arrPos + n);
23+
24+
// To keep track of visited elements. Initialize
25+
// all elements as not visited or false.
26+
std::vector<bool> vis(n, false);
27+
28+
// Initialize result
29+
int ans = 0;
30+
31+
// Traverse array elements
32+
for (int i = 0; i < n; i++) {
33+
// already swapped and corrected or
34+
// already present at correct pos
35+
if (vis[i] || arrPos[i].second == i)
36+
continue;
37+
38+
// find out the number of node in
39+
// this cycle and add in ans
40+
int cycle_size = 0;
41+
int j = i;
42+
while (!vis[j]) {
43+
vis[j] = 1;
44+
45+
// move to next node
46+
j = arrPos[j].second;
47+
cycle_size++;
48+
}
49+
50+
// Update answer by adding current cycle.
51+
if (cycle_size > 0) {
52+
ans += (cycle_size - 1);
53+
}
54+
}
55+
56+
// Return result
57+
return ans;
58+
}
59+
60+
// program to test
61+
int main() {
62+
int arr[] = {6, 7, 8, 1, 2, 3, 9, 12};
63+
int n = (sizeof(arr) / sizeof(int));
64+
std::cout << minSwaps(arr, n);
65+
return 0;
66+
}

0 commit comments

Comments
 (0)