Minimum number of swaps required to sort an array in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of N distinct elements, find the minimum number of swaps required to sort the array


If array is {4, 2, 1, 3} then 2 swaps are required

  • Swap arr[0] with arr[2]
  • Swap arr[2] with arr[3}


1. Create a vector of pair in C++ with first element as array alues and second element as array indices.
2. Sort the vector of pair according to the first element of the pairs.
3. Traverse the vector and check if the index mapped with the value is correct or not, if not then keep swapping until the element is placed correctly and keep counting the number of swaps.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinSwaps(int *arr, int n) {
   vector<pair<int, int>> vec(n);
   for (int i = 0; i < n; ++i) {
      vec[i].first = arr[i];
      vec[i].second = i;
   sort(vec.begin(), vec.end());
   int cnt = 0;
   for (int i = 0; i < n; ++i) {
      if (vec[i].second == i) {
      if (i != vec[i].second) {
   return cnt;
int main() {
   int arr[] = {4, 2, 1, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum swaps = " << getMinSwaps(arr, n) <<
   return 0;

When you compile and execute above program. It generates following output


Minimum swaps = 2
Published on 23-Dec-2019 10:44:51