Pyth, 17 bytes
uXGhaf>FT.:G2]Z)Q
Switching items in a list is really expensive in Pyth. So here's a fun solution, that stretches the rules a little bit. It's probably not valid.
Try it online: Pyth Compiler/Executor
Explanation
First of all, the time complexity of my code is O(n^3)
. But this is not the interesting part. The question doesn't say anything about the complexity.
The critical part is, how I switch two elements in the list. Let's say I want to switch the elements m[3]
and m[4]
. I don't care about the indices 3
and 4
at all. I simply create a second list, that replaces every element equal to m[3]
with the number m[4]
and every number equal to m[4]
with the value m[3]
. Since the list doesn't contain duplicates, this simulates switching these two values. If there were duplicates, like in the input [1, 3, 2, 2]
, the output would be [1, 2, 3, 3]
. And if you give the input [1, 2, 1]
, it would end in an infinite loop. I don't explicitly create the second list, it's just part of Pyth's implementation of the translate-method. If you print out the current lists (see here), it give the correct values, which you would expect.
implicit: Q = input list
u Q set G = Q, update G as long with the following statements,
until it stops changing:
.:G2 all pairs (G[i],G[i+1])
f>FT filter for pairs T, where T[0] > T[1]
a ]Z add to this list of pairs [0]
(ensures that the filtered list is always non-empty)
h take the first element
XG ) translate G by this pair (switches the values T[0] with T[1])
print implicitly at the end