使用JavaScript的解决方案。
首先,我将需要排序的所有元素与它们当前的索引设置好,然后我遍历映射表,仅对需要交换的元素进行排序。
function minimumSwaps(arr) {
const mapUnorderedPositions = new Map()
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== i+1) {
mapUnorderedPositions.set(arr[i], i)
}
}
let minSwaps = 0
while (mapUnorderedPositions.size > 1) {
const currentElement = mapUnorderedPositions.entries().next().value
const x = currentElement[0]
const y = currentElement[1]
if (x-1 !== y) {
mapUnorderedPositions.set(arr[x-1], y)
arr[y] = arr[x-1]
arr[x-1] = x
minSwaps++
}
mapUnorderedPositions.delete(x)
}
return minSwaps
}
如果您有一个输入如7 2 4 3 5 6 1,那么调试的过程将会是这样的:
Map { 7 => 0, 4 => 2, 3 => 3, 1 => 6 }
currentElement [ 7, 0 ]
swapping 1 with 7
[ 1, 2, 4, 3, 5, 6, 7 ]
currentElement [ 4, 2 ]
swapping 3 with 4
[ 1, 2, 3, 4, 5, 6, 7 ]
currentElement [ 3, 2 ]
skipped
minSwaps = 2