We have an unsorted sequence of N numbers (1, 2, 3, 4, ... N). We can sort the whole sequence by swapping adjacent elements in a specific order. Given a sequence, how do I compute the minimum possible swaps required to sort the sequence.
As an example, consider the sequence {4, 2, 5, 3, 1}.
The best way to sort this is using 7 swaps in the following order
- Swap 3, 1: {4, 2, 5, 1, 3}
- Swap 5, 1: {4, 2, 1, 5, 3}
- Swap 4, 2: {2, 4, 1, 5, 3}
- Swap 4, 1: {2, 1, 4, 5, 3}
- Swap 2, 1: {1, 2, 4, 5, 3}
- Swap 5, 3: {1, 2, 4, 3, 5}
- Swap 3, 4: {1, 2, 3, 4, 5}
A greedy algorithm did not prove fruitful. A counterexample was easy to construct. The next obvious choice for approaching the solution was dynamic programming.
Say we have an unsorted sequence: {A1, A2, ...Ai, A(i+1), ..., An}. We know the minimum number of swaps required to sort the sequence {Ai, A(i+1), ..., An} is Min[Ai, A(i+1), ..., An}. The problem is finding Min[A(i-1), Ai, ..., An].
Well, the first thought that popped into my head was to just add the number of steps required to put A(i-1) in the correct place in the already sorted sequence {Ai, ..., An}. This works: the example given in the question has been solved using the exact same method.
But I was not able to prove the validity of this solution. That is often the case with me. When I think I've solved the problem, the best I can do is obtain an 'intuitive' proof for it. I'm in high school and have no formal training in algorithmcs as such. I do it purely out of interest.
Is there rigorous mathematical notation that this problem can be converted into and proved formally? Can this notation be extended to other problems? How? I would appreciate it if it could be presented in a form comprehensible to a high-school-student.
See Question&Answers more detail:
os