You are viewing a single comment's thread. Return to all comments →
The key appears to be that the map is created prior to the sorting, so it indeed is different for the two passes and results in the swaps being done in a different order.
Specifically i in the first for loop is different for the two passes.
i didn't get your explanation of reverse work.can you please explain me in brief manner?
If I understand your question, you are asking why the need to run the algorithm twice, once forward and once in reverse.
The reason for the need to check the reverse case is in the definition of the problem. The requirements are that the array is sorted such the sum of the differences between each two consecutive numbers is minimized. There are two ways to acheive that goal -- ascending and descending sorting the list. The descending sort is the "reverse" in this case.
What he's effectively doing (albeit a little indirectly) is first comparing the input array with an asc-sorted reference, then with a desc-sorted reference and taking the smallest number of swaps of the two. That's how I did it.
To solve it take care of the descending ones too. A counter case to show we also have to take the descending one.
Suppose if the array is-:
3 4 2 5 1
then the output should be 2.
5 4 2 3 1(swap 5 and 3)
5 4 3 2 1(swap 2 and 3)
Hence the answer will be 2.