Say I have an array of numbers, e.g. [0, 1, 2, 3, 4, 5]
and I want to end up with an array, e.g. [2, 1, 4, 0, 5, 3]
. At my disposal, I have a single method that I can use:
move(fromIndex, toIndex)
Thus, to achieve my desired array, I could call the method a number of times:
move(2, 0); // [2, 0, 1, 3, 4, 5]
move(1, 2); // [2, 1, 0, 3, 4, 5] (swapped 2 with 0)
move(4, 2); // [2, 1, 4, 0, 3, 5]
move(3, 4); // [2, 1, 4, 3, 0, 5] (swapped 4 with 0)
move(4, 3); // [2, 1, 4, 0, 3, 5] (swapped 0 with 3)
move(5, 4); // [2, 1, 4, 0, 5, 3] (swapped 5 with 3)
Thus, I also have a list of move()
operations to achieve my desired result. The list of move()
operations can possibly be reduced in size by changing the order and the indexes, to end up with the same result.
Is there an algorithm that I can use on my list of move()
operations to reduce the number of operations to a minimum?