- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum number of swaps required to sort an array in C++
Problem statement
Given an array of N distinct elements, find the minimum number of swaps required to sort the array
Example
If array is {4, 2, 1, 3} then 2 swaps are required
- Swap arr[0] with arr[2]
- Swap arr[2] with arr[3}
Algorithm
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.
Example
#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) { continue; } swap(vec[i].first,vec[vec[i].second].first); swap(vec[i].second,vec[vec[i].second].second); if (i != vec[i].second) { --i; } ++cnt; } return cnt; } int main() { int arr[] = {4, 2, 1, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum swaps = " << getMinSwaps(arr, n) << endl; return 0; }
When you compile and execute above program. It generates following output
Output
Minimum swaps = 2
- Related Articles
- Program to find number of swaps required to sort the sequence in python
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum Swaps required to group all 1’s together in C++
- Minimum swaps required to make a binary string alternating in C++
- Count minimum number of “move-to-front” moves to sort an array in C++
- Minimum operations required to remove an array in C++
- Program to find out the number of shifts required to sort an array using insertion sort in python
- Program to find minimum swaps required to make given anagram in python
- Program to find how many swaps needed to sort an array in Python
- Minimum swaps required to bring all elements less than or equal to k together in C++
- Minimum number of operations required to delete all elements of the array using C++.
- Program to find expected number of shuffle required to sort the elements of an array in Python
- Minimum number of bottles required to fill K glasses in C++
- Minimum Swaps to Make Strings Equal in C++
- Minimum Swaps To Make Sequences Increasing in C++

Advertisements