Pyth, 8 bytes
_ueg#G.p
Try it online!
ueg#G.p
:
u
Repeatedly apply the following function to the input until the result stops changing.
.p
: Generate all permutations of the current list
g#G
:
#
: Filter the list of permutations
g
: On being greater than or equal to
G
: The current list
e
: Take the last permutation in the filtered list. This will only be the same as the current list if the filter only leaves behind one list, because the permutation function .p
always puts its input first.
At this point, we have the maximum permutation of the input, which is in reverse sorted order. _
reverses that to give the sorted list.
Note that Pyth does not have an opposite of g
- there is no less than or equal to builtin.
I wanted to see what the intermediate lists are when sorting with this method. Putting a newline at the end of the code prints all of the intermediate lists:
Try it online!
For the input [0,7,4,1,6,5,2,3]
, here's what the intermediate lists look like:
[0, 7, 4, 1, 6, 5, 2, 3]
[3, 2, 5, 6, 1, 4, 7, 0]
[7, 0, 4, 1, 6, 5, 2, 3]
[7, 3, 2, 5, 6, 1, 4, 0]
[7, 4, 0, 1, 6, 5, 2, 3]
[7, 5, 3, 2, 6, 1, 0, 4]
[7, 6, 4, 0, 1, 2, 3, 5]
[7, 6, 5, 3, 2, 1, 0, 4]
[7, 6, 5, 4, 0, 1, 2, 3]
[7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7]
Basically, what's happening is that at each step, the (reverse) sorted prefix stays, and then the last number larger than the front unsorted number is moved to the front of the unsorted region, and the rest of the unsorted region is reversed. It's like a low-quality selection sort with reversals thrown in for fun.
I think this runs in approximately O(n^2 n!)
time - n!
permutations, n
comparisons each, and O(n)
rounds (at most 2n
, from what I can tell.
[7 2 4 1] -> [4 2 3 1]
. Also, can the CSV list be inside brackets? Also, the specific input format is very suitable for some languages, and bad for others. This makes input parsing a big part for some submissions, and unnecessary for others. \$\endgroup\$