diff --git a/no.of swaps to sort an array b/no.of swaps to sort an array new file mode 100644 index 00000000..4c0e6010 --- /dev/null +++ b/no.of swaps to sort an array @@ -0,0 +1,40 @@ + +#include +using namespace std; + +int findMinSwap(vector &arr, int n) +{ + vector> temp(n); + for (int i = 0; i < n; i++) + { + temp[i].first = arr[i]; + temp[i].second = i; + } + sort(temp.begin(), temp.end()); + int minimum_swaps = 0; + int i = 0; + while (i < n) + { + if (temp[i].second == i or temp[i].first == arr[i]) + { + ++i; + continue; + } + else + { + swap(temp[i].first, temp[temp[i].second].first); + swap(temp[i].second, temp[temp[i].second].second); + if (temp[i].second != i) + i--; + } + minimum_swaps++; + ++i; + } + return minimum_swaps; +} +int main() +{ + vector arr = {1, 4, 3, 2}; + int n = arr.size(); + cout << "Minimum number of swaps required: " << findMinSwap(arr, n) << '\n'; +}