Consider the problem of manipulating a list into a different state where you know the end state.
- Find each 'enclosed subgraph' bigger than one (I'll explain this later on).
- Find the sum of the lengths of the subgraphs and subtract the number of subgraphs.
- There's your answer for the number of swaps.
An 'enclosed subgraph' is a minimal subset of the whole where each item in the initial list is also in the end list.
So if you construct a subgraph with the indices 4,5 and 9 from the initial state and they have the values 10, 20 and 30 then for it to be an 'enclosed subgraph', you should be able to find the values from the end state with the indices 4, 5 and 9 and those values should be 10, 20 and 30 (though not necessarily in that order).
a b c d f e
b a d f c e
This would obviously take 3 swaps. (a <=> b, c <=> d, c <=> f)
Applying the algorithm above, it has:
- 3 'enclosed subgraphs', ([a,b],
- 2 subgraphs with more than one item ([a,b], [c,d,f])
- There are 5 items in all those subgraphs
- 5 - 2 == the answer.
It becomes a little more difficult when you want to do the minimal number of swaps to get it into sorted order, however, it is not impossible.
- Find the sorted order index of each item in the list, if you don't want to move any data, then this is n^2 time.
- Find the 'enclosed subgraphs'.
- Swap items in the list to get to the correct order, but only swap items within the same subgraph.
So, I hope you can see it's not impossible to do the minimal number of swaps to get to sorted order, but it's not worth it, because it requires a ridiculous number of comparisons. Just use heapsort.