Minimum swaps to sort an array (original) (raw)

Last Updated : 14 Jan, 2025

Try it on GfG Practice redirect icon

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.

Table of Content

By Swapping Elements to Correct Positions - O(nlogn) Time and O(n) Space

The idea is to use ahash 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 &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 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.

CycleDetection

Cycle Detection

We 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 &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 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