Minimum swaps to sort an array
Last Updated :
23 Jul, 2025
Given an array arr[] of distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input: arr[] = [2, 8, 5, 4]
Output: 1
Explanation: Swap 8 with 4 to get the sorted array.
Input: arr[] = [10, 19, 6, 3, 5]
Output: 2
Explanation: Swap 10 with 3 and 19 with 5 to get the sorted array.
Input: arr[] = [1, 3, 4, 5, 6]
Output: 0
Explanation: Input array is already sorted.
By Swapping Elements to Correct Positions - O(nlogn) Time and O(n) Space
The idea is to use a hash map to store each element of the given array along with its index. We also create a temporary array that stores all the elements of the input array in sorted order. As we traverse the input array, if the current element arr[i] is not in its correct position, we swap it with the element that should be at i i.e., temp[i]. After this, we increment the swap count and update the indices in the hash map accordingly.
C++
// C++ program to find the minimum no. of swaps required to
// sort an array by swapping elements to correct positions
#include <bits/stdc++.h>
using namespace std;
int minSwaps(vector<int> &arr) {
// Temporary array to store elements in sorted order
vector<int> temp(arr.begin(), arr.end());
sort(temp.begin(), temp.end());
// Hashing elements with their correct positions
unordered_map<int, int> pos;
for(int i = 0; i < arr.size(); i++)
pos[arr[i]] = i;
int swaps = 0;
for(int i = 0; i < arr.size(); i++) {
if(temp[i] != arr[i]) {
// Index of the element that should be at index i.
int ind = pos[temp[i]];
swap(arr[i], arr[ind]);
// Update the indices in the hashmap
pos[arr[i]] = i;
pos[arr[ind]] = ind;
swaps++;
}
}
return swaps;
}
int main() {
vector<int> arr = {10, 19, 6, 3, 5};
cout << minSwaps(arr);
return 0;
}
Java
// Java program to find the minimum no. of swaps required to
// sort an array by swapping elements to correct positions
import java.util.*;
class GfG {
static int minSwaps(int[] arr) {
// Temporary array to store elements in sorted order
int[] temp = arr.clone();
Arrays.sort(temp);
// Hashing elements with their correct positions
HashMap<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < arr.length; i++)
pos.put(arr[i], i);
int swaps = 0;
for (int i = 0; i < arr.length; i++) {
if (temp[i] != arr[i]) {
// Index of the element that should be at index i.
int ind = pos.get(temp[i]);
// Swapping element to its correct position
int tempValue = arr[i];
arr[i] = arr[ind];
arr[ind] = tempValue;
// Update the indices in the hashmap
pos.put(arr[i], i);
pos.put(arr[ind], ind);
swaps++;
}
}
return swaps;
}
public static void main(String[] args) {
int[] arr = {10, 19, 6, 3, 5};
System.out.println(minSwaps(arr));
}
}
Python
# Python program to find the minimum no. of swaps required to
# sort an array by swapping elements to correct positions
def minSwaps(arr):
# Temporary array to store elements in sorted order
temp = sorted(arr)
# Hashing elements with their correct positions
pos = {}
for i in range(len(arr)):
pos[arr[i]] = i
swaps = 0
for i in range(len(arr)):
if temp[i] != arr[i]:
# Index of the element that should be at index i.
ind = pos[temp[i]]
arr[i], arr[ind] = arr[ind], arr[i]
# Update the indices in the dictionary
pos[arr[i]] = i
pos[arr[ind]] = ind
swaps += 1
return swaps
if __name__ == "__main__":
arr = [10, 19, 6, 3, 5]
print(minSwaps(arr))
C#
// C# program to find the minimum no. of swaps required to
// sort an array by swapping elements to correct positions
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static int minSwaps(int[] arr) {
// Temporary array to store elements in sorted order
int[] temp = (int[])arr.Clone();
Array.Sort(temp);
// Hashing elements with their correct positions
var pos = new Dictionary<int, int>();
for (int i = 0; i < arr.Length; i++)
pos[arr[i]] = i;
int swaps = 0;
for (int i = 0; i < arr.Length; i++) {
if (temp[i] != arr[i]) {
// Index of the element that should be at index i.
int ind = pos[temp[i]];
// Swapping element to its correct position
int tempValue = arr[i];
arr[i] = arr[ind];
arr[ind] = tempValue;
// Update the indices in the dictionary
pos[arr[i]] = i;
pos[arr[ind]] = ind;
swaps++;
}
}
return swaps;
}
static void Main(string[] args) {
int[] arr = { 10, 19, 6, 3, 5 };
Console.WriteLine(minSwaps(arr));
}
}
JavaScript
// JavaScript program to find the minimum no. of swaps required to
// sort an array by swapping elements to correct positions
function minSwaps(arr) {
// Temporary array to store elements in sorted order
let temp = [...arr].sort((a, b) => a - b);
// Hashing elements with their correct positions
let pos = new Map();
for (let i = 0; i < arr.length; i++) {
pos.set(arr[i], i);
}
let swaps = 0;
for (let i = 0; i < arr.length; i++) {
if (temp[i] !== arr[i]) {
// Index of the element that should be at index i.
let ind = pos.get(temp[i]);
[arr[i], arr[ind]] = [arr[ind], arr[i]];
// Update the indices in the map
pos.set(arr[i], i);
pos.set(arr[ind], ind);
swaps++;
}
}
return swaps;
}
// Driver Code
const arr = [10, 19, 6, 3, 5];
console.log(minSwaps(arr));
Using Cycle Detection - O(nlogn) Time and O(n) Space
This approach uses cycle detection method to find out the minimum number of swaps required to sort the array. If an element is not in its correct position, it indicates that it is a part of a cycle with one or more other elements that also need to be moved. For example, if element A is in the position of element B, and element B is in the position of element C, and so on, until it comes back to A, it forms a cycle. And to sort the elements in the cycle, we need cycleSize - 1 swaps, as each swap places one element in its correct position, and the last element will automatically be in its correct place.
Cycle DetectionWe use a hash map to store the original indices of each element and a visited array to mark elements that have already been included in a cycle. Next, we sort the array. As we traverse it, if an element hasn’t been visited and isn’t in its correct position, we trace the cycle formed by the misplaced elements and find its size. The swap count is then updated by cycleSize - 1.
C++
// C++ program to find no. of swaps required to
// sort the array using cycle detection method
#include <bits/stdc++.h>
using namespace std;
int minSwaps(vector<int> &arr) {
int n = arr.size();
// Array to Keep track of those elements
// who already been included in the cycle
bool vis[n] = {0};
// Hashing elements with their original positions
unordered_map<int, int> pos;
for (int i = 0; i < n; i++)
pos[arr[i]] = i;
sort(arr.begin(), arr.end());
int swaps = 0;
for (int i = 0; i < n; i++) {
// Already a part of another cycle Or
// in its correct position
if (vis[i] || pos[arr[i]] == i)
continue;
int j = i, cycleSize = 0;
// We make a cycle until it comes
// back to first element again.
while (!vis[j]) {
vis[j] = true;
// move to next element of the cycle
j = pos[arr[j]];
cycleSize++;
}
// Update answer by adding current cycle.
if (cycleSize > 0) {
swaps += (cycleSize - 1);
}
}
return swaps;
}
int main() {
vector<int> arr = { 10, 19, 6, 3, 5 };
cout << minSwaps(arr);
return 0;
}
Java
// Java program to find no. of swaps required to
// sort the array using cycle detection method.
import java.util.Arrays;
import java.util.HashMap;
class GfG {
static int minSwaps(int[] arr) {
int n = arr.length;
// Array to Keep track of those elements
// who already been included in the cycle.
boolean[] vis = new boolean[n];
// Hashing elements with their original positions
HashMap<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < n; i++)
pos.put(arr[i], i);
Arrays.sort(arr);
int swaps = 0;
for (int i = 0; i < n; i++) {
// Already a part of another cycle Or
// in its correct position
if (vis[i] || pos.get(arr[i]) == i)
continue;
int j = i, cycleSize = 0;
// We make a cycle until it comes
// back to first element again.
while (!vis[j]) {
vis[j] = true;
// move to next element of the cycle
j = pos.get(arr[j]);
cycleSize++;
}
// Update answer by adding current cycle.
if (cycleSize > 0) {
swaps += (cycleSize - 1);
}
}
return swaps;
}
public static void main(String[] args) {
int[] arr = {10, 19, 6, 3, 5};
System.out.println(minSwaps(arr));
}
}
Python
# Python program to find no. of swaps required to
# sort the array using cycle detection method.
def minSwaps(arr):
n = len(arr)
# Array to Keep track of those elements
# who already been included in the cycle.
vis = [False] * n
# Hashing elements with their original positions
pos = {}
for i in range(len(arr)):
pos[arr[i]] = i
arr.sort()
swaps = 0
for i in range(n):
# Already a part of another cycle Or
# in its correct position
if vis[i] or pos[arr[i]] == i:
continue
j, cycleSize = i, 0
# We make a cycle until it comes
# back to first element again.
while not vis[j]:
vis[j] = True
# move to next element of the cycle
j = pos[arr[j]]
cycleSize += 1
# Update answer by adding current cycle.
if cycleSize > 0:
swaps += (cycleSize - 1)
return swaps
if __name__ == "__main__":
arr = [10, 19, 6, 3, 5]
print(minSwaps(arr))
C#
// C# program to find no. of swaps required to
// sort the array using cycle detection method.
using System;
using System.Collections.Generic;
class GfG {
static int minSwaps(int[] arr) {
int n = arr.Length;
// Array to Keep track of those elements
// who already been included in the cycle.
bool[] vis = new bool[n];
// Hashing elements with their original positions
Dictionary<int, int> pos = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
pos[arr[i]] = i;
Array.Sort(arr);
int swaps = 0;
for (int i = 0; i < n; i++) {
// Already a part of another cycle Or
// in its correct position
if (vis[i] || pos[arr[i]] == i)
continue;
int j = i, cycleSize = 0;
// We make a cycle until it comes
// back to first element again.
while (!vis[j]) {
vis[j] = true;
// move to next element of the cycle
j = pos[arr[j]];
cycleSize++;
}
// Update answer by adding current cycle.
if (cycleSize > 0) {
swaps += (cycleSize - 1);
}
}
return swaps;
}
static void Main(string[] args) {
int[] arr = {10, 19, 6, 3, 5};
Console.WriteLine(minSwaps(arr));
}
}
JavaScript
// JavaScript program to find no. of swaps required to
// sort the array using cycle detection method.
function minSwaps(arr) {
let n = arr.length;
// Array to Keep track of those elements
// who already been included in the cycle.
let vis = new Array(n).fill(false);
// Hashing elements with their original positions
let pos = new Map();
arr.forEach((value, index) => pos.set(value, index));
arr.sort((a, b) => a - b);
let swaps = 0;
for (let i = 0; i < n; i++) {
// Already a part of another cycle Or
// in its correct position
if (vis[i] || pos.get(arr[i]) === i)
continue;
let j = i, cycleSize = 0;
// We make a cycle until it comes
// back to first element again.
while (!vis[j]) {
vis[j] = true;
// move to next element of the cycle
j = pos.get(arr[j]);
cycleSize++;
}
// Update answer by adding current cycle.
if (cycleSize > 0) {
swaps += (cycleSize - 1);
}
}
return swaps;
}
// Driver Code
let arr = [10, 19, 6, 3, 5];
console.log(minSwaps(arr));
Related Article:
Number of swaps to sort when only adjacent swapping allowed
Minimum Swaps to Sort | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem