【发布时间】:2020-05-04 15:17:16
【问题描述】:
我想找到对数组进行排序的最小交换次数。 (保证数组没有重复。)我发现一个帖子基本上使用图表来做到这一点:Compute the minimal number of swaps to order a sequence
但我想知道我是否也可以通过运行选择排序并计算交换次数来做到这一点。 (见下面的代码。)这种方法正确吗?或者有没有会给出错误结果的情况?
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;
}
【问题讨论】: