Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Minimum number of swaps required to sort an array

Easy
0/40
Average time to solve is 10m
profile
Contributed by
32 upvotes
Asked in companies
IBMHikeSamsung

Problem statement

You have been given an array 'ARR' of 'N' distinct elements.

Your task is to find the minimum no. of swaps required to sort the array.

For example:
For the given input array [4, 3, 2, 1], the minimum no. of swaps required to sort the array is 2, i.e. swap index 0 with 3 and 1 with 2 to form the sorted array [1, 2, 3, 4].
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.

The first line of each test case contains an integer ‘N’ representing the size of the input array.

The second line of each test case contains the 'N' elements of the array separated by a single space.
Output Format:
For each test case, print a single line containing a single integer which represents the minimum no. of swaps required to sort the array.

The output for each test case is in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 1000
0 <= ARR[i] <= 10 ^ 9

Where 'ARR[i]' is the value of the input array elements.

Time Limit: 1 sec
Sample Input 1:
2
4
4 3 2 1
5
1 5 4 3 2
Sample Output 1:
2
2
Explanation of Sample Input 1:
For the first test case, swap index 0 with 3 i.e. 4 -> 1 and 1 with 2 i.e. 3 -> 2 to form the sorted array {1, 2, 3, 4}.

For the second test case, swap index 1 with 4 i.e. 5 -> 2 and 2 with 3 i.e. 4 -> 3 to form the sorted array {1, 2, 3, 4, 5}.
Sample Input 2:
2
4
1 2 3 4
6
3 5 2 4 6 8
Sample Output 2:
0
3
Hint

Swap every element of the given array with its right index, if it is not at the right place.

Approaches (2)
Naive Approach

While iterating over the array, check the current element, and if not in the correct place, replace that element with the index of the element which should have come in this place.

 

Below is the algorithm:

  1. Create a copy of the given input array and store it in temp.
  2. Sort the temp array.
  3. Iterate over the input array, and check whether the current element is at the right place or not by comparing it with temp[i].
    1. If it is the right place, no need to do anything.
    2. Else, increase the count by 1 and swap the current element with the right index. So that array will remain sorted till index i.
Time Complexity

O(N ^ 2), where ‘N’ is the size of the given array.

 

Since we are using indexOf() function to check the right index of every element of input array, having the worst case time complexity of O(N) for each array element. So, the overall complexity is O(N ^ 2).

Space Complexity

O(N), where ‘N’ is the size of the given array.

 

Since we are using a temp array to store the sorted form of a given input array, thus, the space complexity will be O(N).

Code Solution
(100% EXP penalty)
Minimum number of swaps required to sort an array
All tags
Sort by
Search icon

Interview problems

min swap easy soln

#include<bits/stdc++.h>

int minSwaps(vector<int> &arr)

{

    int n=arr.size();

vector<pair<int,int>>v(n);

for(int i=0;i<n;i++){

    v[i]={arr[i],i};

}

sort(v.begin(),v.end());

int cnt=0;

for(int i=0;i<n;i++){

    if(v[i].second==i){

        

    }

    else{

        swap(v[i],v[v[i].second]);

        cnt++;

        i--;

    }

}

return cnt;

 

}

65 views
0 replies
0 upvotes

Interview problems

C++ solution please upvote

int minSwaps(vector<int> &arr)
{ 
  int n = arr.size();
    int count = 0;
    
    vector<int> arr2 = arr;
    sort(arr2.begin(), arr2.end());

   
    for (int i = 0; i < n; i++) {
        
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j;
            }
        }

       
        if (minIdx != i) {
            swap(arr[i], arr[minIdx]);
            count++;
        }

       
        if (equal(arr.begin(), arr.end(), arr2.begin())) {
            return count;
        }
    }

    return count;
}
58 views
0 replies
1 upvote

Interview problems

EASY SOLUTION C++

int minSwaps(vector<int> &arr)

{

    // using selection sort.

    int n = arr.size();

    int cnt = 0;

    for(int i=0; i<n-1; i++){

        int min = i;

        for(int j=i+1; j<n; j++){

            if(arr[j] < arr[min])

                min = j;

        }

        if(min != i){

            swap(arr[min], arr[i]);

            cnt++;

        }

    }

    return cnt;

}

104 views
0 replies
1 upvote

Interview problems

Simple java Solution

import java.util.*;

 

public class Solution {

 

    public static class Pair

    {

        int n;

        int i;

        Pair(int element,int index)

        {

            n=element;

            i=index;

        }

    }

    public static int minSwaps(int[] arr) {

        // Write your code here.

        List<Pair>  lst=new ArrayList<>();

        for(int i=0;i<arr.length;i++)

        {

            lst.add(new Pair(arr[i],i));

        }

        Comparator<Pair> cmp=(a,b)->(a.n-b.n);

        Collections.sort(lst,cmp);

int swap=0;

        int k=0;

        int n=arr.length;

        while(k<n)

        {

            Pair p=lst.get(k);

            if(p.i!=k)

            {

                swap++;

                

                Pair temp=lst.get(k);

                lst.set(k,lst.get(p.i));

                lst.set(p.i,temp);

            }

            else

            {

                k++;

            }

        }

        return swap;

    }

}

63 views
0 replies
0 upvotes

Interview problems

easy c++ code || Upvote

int minSwaps(vector<int> &arr)

{

    // Write your code here.

    vector<pair<int,int>>v1;

    for(int i=0; i<arr.size(); ++i)

    {

        v1.push_back({arr[i],i});

    }

    sort(v1.begin(),v1.end());

    int count=0;

    for(int i=0; i<arr.size(); ++i)

    {

        pair<int,int>p = v1[i];

        int value = p.first;

        int index = p.second;

        if(index==i)

        {

            continue;

        }

        else

        {

            swap(v1[i],v1[index]);

            count++;

            i--;

        }

    }

    return count;

}

188 views
0 replies
1 upvote

Interview problems

Let make it Easy !!!

#include<bits/stdc++.h>
int minSwaps(vector<int> &arr)
{
	vector<pair<int,int>>map(arr.size());

	for(int i=0;i<arr.size();i++){
          map[i] = {arr[i],i};
    }
	
	sort(map.begin(),map.end());

	int swaps =0;

	for(int i=0;i<arr.size();i++){
		if(map[i].second == i){
			continue;
		}

		swap(map[i], map[map[i].second]);
		swaps++;
		i--;
	}

	return swaps;

}
127 views
0 replies
0 upvotes

Interview problems

Easy and short

#include <climits> #include <iostream> #include <vector> using namespace std;

int arraySortedOrNot(vector<int> &arr, int n) {    if (n == 1 || n == 0)        return 1;    if (arr[n - 1] < arr[n - 2])        return 0;    return arraySortedOrNot(arr, n - 1); }

int minSwaps(vector<int> &arr) {    int N = arr.size();    int count = 0;

   for (int i = 0; i < N - 1; ++i) {        int minIndex = i;        for (int j = i + 1; j < N; ++j) {            if (arr[j] < arr[minIndex]) {                minIndex = j;            }        }

       if (minIndex != i) {            swap(arr[i], arr[minIndex]);            count++;        }

       if (arraySortedOrNot(arr, N)) {            break;        }    }

   return count; }

 

73 views
0 replies
0 upvotes

Interview problems

easy cpp

#include <bits/stdc++.h>

using namespace std;

int arraySortedOrNot(vector<int> &arr, int n) {

  if (n == 1 || n == 0)

    return 1;

  if (arr[n - 1] < arr[n - 2])

    return 0;

 return arraySortedOrNot(arr, n - 1);

}

int minSwaps(vector<int> &arr) {

  int N = arr.size();

  int count = 0;

  if (arraySortedOrNot(arr, N)) {

    return count;

  } else {

    int min;

    int k;

    for (int i = 0; i < N; i++) {

    min=INT_MAX;

      for (int j = i; j < N; j++) {

        if (arr[j] < min) {

          min = arr[j];

          k = j;

        }

      }

      if (k!= i) {

        int temp = arr[i];

        arr[i] = arr[k];

        arr[k] = temp;

    count++;

      }

      if (arraySortedOrNot(arr, N)) {

        return count;

      } 

    }

  }

}

77 views
0 replies
0 upvotes

Interview problems

easy c++solution

int minSwaps(vector<int> &arr)

{

    // Write your code here.

    int n=arr.size();

    pair<int ,int>arrpos[n];

    for(int i=0;i<n;i++){

        arrpos[i].first=arr[i];

        arrpos[i].second=i;

 

    }

    sort(arrpos,arrpos+n);

 

    vector<bool>vis(n,false);

    int ans=0;

    for(int i=0;i<n;i++){

        if(vis[i]||arrpos[i].second==i){

            continue;

        }

        int cycle_size=0;

        int j=i;

        while(!vis[j]){

            vis[j]=1;

            j=arrpos[j].second;

            cycle_size++;

        }

        if(cycle_size>0){

            ans +=(cycle_size-1);

        }

    }

     return ans;

 

}

270 views
0 replies
0 upvotes

Interview problems

Best Optimized solution ever with explanation

In this solution, we perform selection sort while keeping track of the number of swaps performed. The selection sort algorithm selects the minimum element from the unsorted portion of the array and places it at the correct position in the sorted portion. By counting the number of swaps, we can determine the minimum number of swaps required to sort the array

 

public class Solution {
	public static int minSwaps(int[] arr) {
		// Write your code here.

		int n = arr.length;
        int swaps = 0;

        for (int i = 0; i < n; i++) {
            // Find the index of the minimum element from i to n-1
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap the minimum element with the current element at index i
            if (minIndex != i) {
                int temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
                swaps++;
            }
        }

        return swaps;
	}
}

 

java

258 views
0 replies
2 upvotes
Full screen
Console