# Find the minimum number of swaps to sort unsorted array.

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. Find the minimum number of swaps required to sort the array in ascending order.

**Example**

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 swaps to sort the array.

**Function Description**

Complete the function minimumSwaps in the editor below.

minimumSwaps has the following parameter(s):

- int arr[n]: an unordered array of integers

**Returns**

- int: the minimum number of swaps to sort the array

**Input Format**

The first line contains an integer, , the size of .

The second line contains space-separated integers .

**Constraints**

**Sample Input 0**

`4`

4 3 1 2

**Sample Output 0**

`3`

**Sample Input 1**

`5`

2 3 4 1 5

**Sample Output 1**

`3`

**Explanation :**

In order to solve this , we have very simple algorithm. we need to index the array start from 1 to n. we will check the value present at index is matching with that index or not. If it does not match , we will get the value present at index, that will be our swapping position. For example : we have this array

A[] = [4,3,1,2]. At index 1, we have value ‘4’ present so we will swap the index value 4 to 1. After this , our array would look like this [2,3,1,4].

Again we will check the index value present at 1. Now it has ‘2’. We will swap the value between index 1 and 2. After this array would be like this

[3,2,1,4]

Again we will swap the first value with 3rd Index and our array would become — [1,2,3,4].

Finally our array is sorted. This is very simple algorithm.

I hope i have explained this well. Happy Learning .

staticintminimumSwaps(int[] arr) {intswap = 0 ;for(inti = 0 ;i < arr.Length ;i++)

{while(arr[i]!=i+1)

{

if(arr[i] != i+1)

{

intswapIndex = arr[i]-1;

inttemp = arr[swapIndex];

arr[swapIndex] = arr[i];

arr[i] = temp;

swap++;

}

}

}returnswap;

}