Minimum Swaps 2 Solution - The Coding Shala

Home >> Programming Questions >> Minimum Swaps 2

Minimum Swaps 2 Solution

In this post, you will learn how to solve the Minimum Swaps 2 Problem and its solution in Java.

You are given an unordered array consisting of consecutive integers  [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
For example, given the array arr = [7,1,3,2,4,5,6] we perform the following steps:

i   arr                          swap (indices)

0   [7, 1, 3, 2, 4, 5, 6]   swap (0,3)

1   [2, 1, 3, 7, 4, 5, 6]   swap (0,1)

2   [1, 2, 3, 7, 4, 5, 6]   swap (3,4)

3   [1, 2, 3, 4, 7, 5, 6]   swap (4,5)
4   [1, 2, 3, 4, 5, 7, 6]   swap (5,6)
5   [1, 2, 3, 4, 5, 6, 7]
It took  5 swaps to sort the array.

Minimum Swaps 2 Java Program

All the given elements of the array are from 1 to n and there are duplicates so we can solve this problem by comparing elements with their original position in the sorted array.
Java Program: 

public class Solution {
    // Complete the minimumSwaps function below.
    static int minimumSwaps(int[] arr) {
        int count = 0;
        for(int i=0;i<arr.length;i++){
            if(arr[i]==i+1) continue;
            count++;
            int tmp = arr[i];
            arr[i] = arr[tmp-1];
            arr[tmp-1] = tmp;
            i--;
        }
        return count;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala