kut*_*tta 5 arrays sorting algorithm
如果给定一个由 1 和 0 组成的数组,有什么好的算法可以显示将所有 1 组合在一起所需的最小相邻交换数。1 不需要在数组中的任何特定位置分组。它们只需要在提供最少相邻交换数量的任何地方分组。
例如,如果数组看起来像这样......
1,0,0,1,1,0,1
...相邻交换的最小数量为 3,因为您将以索引 4 为中心并执行以下交换:
交换索引 0 和 1,结果:
0,1,0,1,1,0,1
交换索引 1 和 2,导致:
0,0,1,1,1,0,1
交换索引 5 和 6,结果:
0,0,1,1,1,1,0
任何人都有一个很好的算法来找到任何 1 和 0 数组的最小相邻交换数?
更新:
该算法仅通过获取所有 1 索引的数组来确定中心。该数组的中心将始终保存中心索引。快多了。
oneIndices = array of indices of all 1's in the input
middleOfOnesIndices = round(oneIndices.length/2)-1 // index to the center index
minimumSwaps = 0
foreach index i of oneIndices
minimumSwaps += aboluteValue(oneIndices[middleOfOneIndices]-oneIndices[i])-absoluteValue(middleOfOneIndices-i);
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴,可以看到它的实际效果:
https://jsfiddle.net/3pmwrk0d/6/
这是一个有趣的。谢谢你的提问。