forked from Ayush7614/Daily-Coding-DS-ALGO-Practice
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinimum_swaps_required.cpp
More file actions
51 lines (37 loc) · 891 Bytes
/
Minimum_swaps_required.cpp
File metadata and controls
51 lines (37 loc) · 891 Bytes
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
// Defining the header files used for the program
#include<bits/stdc++.h>
#include <vector>
#include <algorithm>
using namespace std;
// making a function that counts swap times minimum
int swap(int a[], int n)
{
vector<pair<int,int> > v(n);
for(int i=0; i<n; i++)
v[i] = {a[i],i};
sort(v.begin(),v.end());
int c=0;
for(int i=0; i<n; i++)
{
if(v[i].second == i)
continue;
else
{
c++;
swap(v[i],v[v[i].second]);
i--;
}
}
return c; // returns the minimum swap count
}
// Driver Code
int main()
{
int n;
cin>>n; //No of elements to be stored
int a[n]; //array defined
for(int i=0; i<n; i++)
cin>>a[i]; //loop for storing array elements
int c = swap(a,n); // Calling the function
cout<<c;
}