Chris is given a list of numbers to sort in ascending order. He was told that swapping any two elements incurs a cost of ( and are the indices of the elements respectively). What is the minimum cost for Chris to sort the given list ?
As an explicit example, for the list
1 3 2
the minimum cost is 1.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Swapping costs us ( i − j ) 2 , can we do better? Suppose that we want to swap
x
andy
in the listx 0 0 y
. We can actually do so by swappingy
to the left 3 times, and thenx
to the right 2 times. See the illustration below :This will only costs 5 which is smaller than 9 of that we use the given swap operation. In general, swapping indices i and j only costs us 2 ∣ i − j ∣ − 1 .
The much cheaper costs operation is due to the "shifting" of numbers. From now on we shall use shifting instead of swapping because it performs better and gives us more flexibility (ie. when you only want to move the number to a position without affecting the order of other numbers). Since swapping a number to the left is the same as swapping the left of that number to the right, we can confidently say that we only need to perform shifting to one of the direction, we use left in this solution.
When the number can only shift to the left, we definitely don't want to shift over a number that is smaller than it because in the future we will need that smaller number to shift left again to get back to its correct position. Furthermore, if the number on the left is greater, shift over it is inevitable. Hence, each time we find the smallest number in the unsorted array, and shift it to the left until its correct position. Perform this until the array is sorted. See the illustration below on how to use only 4 shifts to sort the array
4 1 3 2
:C++ program
Not an optimal code since there are only 900 numbers in the array.