I want to find the minimal number of swaps to sort an array. (The array is guaranteed not to have duplicates.) I found a post that does this basically using a graph: Compute the minimal number of swaps to order a sequence
But I was wondering if I can also do this by running selection sort and counting the number of swaps. (See code below.) Is this approach correct? Or is there a case where it will give the wrong result?
int minSwaps(int[] A, int n) {
int numSwaps = 0;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (A[j] < A[minIndex])
minIndex = j;
}
if (minIndex != i) {
numSwaps++;
int temp = A[minIndex];
A[minIndex] = A[i];
A[i] = temp;
}
}
return numSwaps;
}