Minimum swaps to sort an array
Last Updated :
14 Jan, 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
Similar Reads
Depth First Search or DFS for a Graph In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
DFS in different language
Iterative Depth First Traversal of Graph Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
10 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS) Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Difference between BFS and DFS Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
2 min read
Depth First Search or DFS for disconnected Graph Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Disconnected Graph Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given sour
7 min read
Printing pre and post visited times in DFS of a graph Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored
8 min read
Tree, Back, Edge and Cross Edges in DFS of Graph Given a directed graph, the task is to identify tree, forward, back and cross edges present in the graph.Note: There can be multiple answers.Example:Input: GraphOutput:Tree Edges: 1->2, 2->4, 4->6, 1->3, 3->5, 5->7, 5->8 Forward Edges: 1->8 Back Edges: 6->2 Cross Edges: 5-
9 min read
Transitive Closure of a Graph using DFS Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
8 min read
Variations of DFS implementations