#K91427. Minimum Swaps to Sort Array
Minimum Swaps to Sort Array
Minimum Swaps to Sort Array
You are given an array of distinct integers. Your task is to determine the minimum number of swaps required to sort the array in ascending order.
The key observation is that the array can be decomposed into one or more cycles. For each cycle with ( k ) elements, the number of swaps required is ( k - 1 ). The total number of swaps is then the sum of swaps over all cycles:
[
\text{Minimum Swaps} = \sum_{\text{cycle}} (\text{cycle size} - 1) ]
For example, consider the array [4, 3, 1, 2]. The minimum number of swaps required to sort it is 3.
inputFormat
The input is read from standard input (stdin). The first line contains an integer ( n ) representing the number of elements in the array. The second line contains ( n ) space-separated integers representing the array.
outputFormat
Output a single integer which is the minimum number of swaps required to sort the array in ascending order. The output should be written to standard output (stdout).## sample
4
4 3 1 2
3