How do I figure out the minimum number of swaps to sort a list in-place?

Posted by sova on Programmers See other posts from Programmers or by sova
Published on 2011-01-04T05:54:29Z Indexed on 2011/01/04 5:58 UTC
Read the original article Hit count: 245

Filed under:
|

In-place sorting is essentially swapping elements without using extra storage, correct?

How can I find the minimum number of swaps required for a list?

A C D Q R Z   E   // input
| | | > > > <<<   // movement
A C D E Q R   Z   // output

Swapping:

A C D Q R Z E

swap Q with E, ACDERZQ
swap R with Q, ACDEQZR
swap R with Z, ACDEQRZ. done.

3 swaps.

Shifting items left or right is essentially swapping, but I want the optimal number for plucking an item out of line and switching its place with another.

© Programmers or respective owner

Related posts about sorting

Related posts about list