i have a task in hand where i need to sort a n
-length list whose items are 0~n-1 without duplicates by repeatedly swapping two items.
i would like to keep swapping arr[0]
with the item whose index is arr[0]
(i.e. arr[arr[0]]
) until arr[0] = 0
, then repeatedly do the same to arr[1]
through arr[n-1]
.
for example, if the list is arr=[1,2,0,4,3]
, i'd first swap arr[0]
with arr[arr[0]]
(i.e. arr[1]
), getting [2,1,0,4,3]
, then swap arr[0]
with arr[arr[0]]
again, (this time arr[2]
), getting [0,1,2,4,3]
, then swap arr[3]
with arr[4]
, getting the final result [0,1,2,3,4]
.
the code is as follows:
while i < len(arr) - 1:
while arr[i] != i:
arr[i], arr[arr[i]] = arr[arr[i]], arr[i] # not working
arr[arr[i]], arr[i] = arr[i], arr[arr[i]] # working
i += 1
the problem is that when i do arr[i], arr[arr[i]] = arr[arr[i]], arr[i]
, it does not work (it only makes arr[i] = arr[arr[i]]
).
swapping in the opposite order (i.e. arr[arr[i]], arr[i] = arr[i], arr[arr[i]]
) works.
any one could explain what was going on in the background and why the first case did not work? thanks.