Challenge
Given a non-empty array of integers, e.g.:
[5, 2, 7, 6, 4, 1, 3]
First sever it into arrays where no item is larger than the previous (i.e. non-ascending arrays):
[5, 2] [7, 6, 4, 1] [3]
Next, reverse each array:
[2, 5] [1, 4, 6, 7] [3]
Finally, concatenate them all together:
[2, 5, 1, 4, 6, 7, 3]
This should be what your program outputs/function returns. Repeat this procedure enough times and the array will be fully sorted.
Rules
- Input and output may be given through any standard methods, and may be in any reasonable array format.
- The input array will never be empty, but may contain negatives and/or duplicates.
- The absolute value of each integer will always be less than 231.
Test cases
Hopefully these cover all edge cases:
[1] -> [1]
[1, 1] -> [1, 1]
[1, 2] -> [1, 2]
[2, 1] -> [1, 2]
[2, 3, 1] -> [2, 1, 3]
[2, 1, 3] -> [1, 2, 3]
[2, 1, 2] -> [1, 2, 2]
[2, 1, 1] -> [1, 1, 2]
[3, 1, 1, 2] -> [1, 1, 3, 2]
[3, 2, 1, 2] -> [1, 2, 3, 2]
[3, 1, 2, 2] -> [1, 3, 2, 2]
[1, 3, 2, 2] -> [1, 2, 2, 3]
[1, 0, 5, -234] -> [0, 1, -234, 5]
[1, 0, 1, 0, 1] -> [0, 1, 0, 1, 1]
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]
[5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5]
[2, 1, 5, 4, 3] -> [1, 2, 3, 4, 5]
[2, 3, 1, 5, 4] -> [2, 1, 3, 4, 5]
[5, 1, 4, 2, 3] -> [1, 5, 2, 4, 3]
[5, 2, 7, 6, 4, 1, 3] -> [2, 5, 1, 4, 6, 7, 3]
[-5, -2, -7, -6, -4, -1, -3] -> [-5, -7, -2, -6, -4, -3, -1]
[14, 5, 3, 8, 15, 7, 4, 19, 12, 0, 2, 18, 6, 11, 13, 1, 17, 16, 10, 9] -> [3, 5, 14, 8, 4, 7, 15, 0, 12, 19, 2, 6, 18, 11, 1, 13, 9, 10, 16, 17]
Scoring
This is code-golf, so the shortest code in bytes wins.
O(n^2)
\$\endgroup\$O(n)
. swap first and last elements then swap second and second last elements etc, when you get to the middle stop. \$\endgroup\$O(n)
, but reversing can be built right into the algorithm (that's what my JS answer does); since each iteration loops over each item in the array once, a single iteration isO(n)
. (I think...) \$\endgroup\$