ここでの問題は、実際のデータの交換には非常にコストがかかることですが、比較すると比較的安価です。
まず、通常の並べ替えアルゴリズムを使用して、配列内の各要素の位置を見つけます。それを行うためのアルゴリズムはたくさんあります。たとえば、クイックソートや単なるバブルソート、挿入ソートなどです。
これで、各要素がどこに行くべきかがわかったので、ここから元のデータをソートされた位置に移動するための最適な一連のスワップを見つけることができます。
擬似コードの例:
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