> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/array/sorting/minimum-swaps-to-sort.md).

# Minimum Swaps to Sort

## Problem Statement

\
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.

\
**Example 1:**

<pre><code><strong>Input:
</strong>nums = {2, 8, 5, 4}
<strong>Output:
</strong>1
<strong>Explaination:
</strong>swap 8 with 4.
</code></pre>

**Example 2:**

<pre><code><strong>Input:
</strong>nums = {10, 19, 6, 3, 5}
<strong>Output:
</strong>2
<strong>Explaination:
</strong>swap 10 with 3 and swap 19 with 5.
</code></pre>

\
**Your Task:**\
You do not need to read input or print anything. Your task is to complete the function **minSwaps()** which takes the **nums** as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.&#x20;

\
**Expected Time Complexity:** O(nlogn)\
**Expected Auxiliary Space:** O(n)

\
**Constraints:**\
1 ≤ n ≤ 105\
1 ≤ numsi ≤ 106\ <br>

## Intuition

```
We intend to send all elements to the correct position

Hence, Maintain a array where we sort the array
MAintain a map which contains actual position of elements, 
Can iterate over this sorted and maintain the indices

Now compare the actual array with sorted and start sending the elements to the
correct position

You notice we can send them in min swaps
```

### Links

<https://practice.geeksforgeeks.org/problems/minimum-swaps/1>

### Video Links

### Approach 1:

```
Map and sorting
```

{% code title="C++" lineNumbers="true" %}

```cpp

class Solution 
{
    public:
	int minSwaps(vector<int>&nums){
	    vector<int> arr(nums);
        unordered_map<int,int> mp;
        sort(arr.begin(), arr.end());
        int count = 0;

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

        int left = 0;
        int right = 0;

        while(right < arr.size()){
            if(arr[left] != nums[right]){
                int pos = mp[nums[right]];
                swap(nums[right], nums[pos]);
                count++;
            }

            else{
                left++;
                right++;
            }
        }
        
        return count;
	}
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###
