From 3f5065e89526718a7c6c9de8b548ab815f3d52c1 Mon Sep 17 00:00:00 2001 From: Nupur Hardiya <113535580+NupurHardiya@users.noreply.github.com> Date: Sun, 16 Oct 2022 16:32:24 +0530 Subject: [PATCH] Create no.of swaps to sort an array --- no.of swaps to sort an array | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 no.of swaps to sort an array 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'; +}