我认为这里的问题是数据的实际交换非常昂贵,但比较相对便宜。
我将首先使用常规排序算法来找出数组中每个元素的位置。有很多算法可以做到这一点,例如快速排序或只是冒泡排序或插入排序。
现在我们知道每个元素应该去哪里,从这里开始,我们可以找到最佳的交换序列,将原始数据放到排序位置。
伪代码示例:
compare(proxy1, proxy2)
return compare(proxy1.data, proxy2.data)
smartSort(unsorted)
swaps = []
count = size(unsorted)
// create a proxy for all elements
proxiesOrig = [ new proxy(data) | for unsorted as data ]
// and make a copy which we are going to sort
proxiesSort = shallowCopy(proxiesOrig)
sort(proxiesOrig) // Do a regular sort here, using the compare function above
// now note the location of each target
// because we made a shallow copy, the location will also be marked in the
// proxiesOrig list
for i = 1 .. count
proxiesSort[i].location = i
// Now the proxiesOrig is the unsorted list
// with location information to where everything needs to go
for i = 1 .. count
while (proxiesOrig[i].location <> i)
// swap the proxy on location i with the one to where i needs to go
swap(proxiesOrig, i, proxiesOrig[i].location)
// and record it
swaps.add(i, proxiesOrig[i].location)
return swaps