Intermediate Level

Implement the minimumSwapsToSortSmallArray method that returns the minimum number of swaps needed to sort the array.

The input contains an integer array nums and its length size. Your task is to return the minimum number of swaps required to sort the array in ascending order.

One swap can exchange values at any two positions. For example, [4,3,2,1] can be sorted using 2 swaps.

Example 1
Input:
nums (int[]) = [4,3,2,1]
size (int) = 4
Return:
(int) 2
Example 2
Input:
nums (int[]) = [1,5,4,3,2]
size (int) = 5
Return:
(int) 2
Example 3
Input:
nums (int[]) = [1,2,3]
size (int) = 3
Return:
(int) 0

Compare the current array with its sorted version.

For each position, check which value should be there in the sorted array. If the current value is not correct, swap it with the position where the correct value currently exists. Each such operation fixes at least one position, so the total count gives the minimum swaps for arrays with distinct values.

Pseudocode:

function minimumSwapsToSortSmallArray(nums, size):
    sortedNums = copy of nums sorted in ascending order
    position = map each value to its current index in nums
    swaps = 0
    for i from 0 to size - 1:
        correctValue = sortedNums[i]
        if nums[i] != correctValue:
            currentValue = nums[i]
            correctIndex = position[correctValue]
            swap nums[i] and nums[correctIndex]
            position[currentValue] = correctIndex
            position[correctValue] = i
            swaps++
    return swaps
Run your code to see the result.