Someone else has done a similar challenge:
Recursive algorithm works without return statement? (Runs really fast)
For this challenge, the strings have no leading zeroes and are to be treated as integers. A longer string is greater than a shorter string. A length compare needs to be done first and only if the lengths are equal should the strings be compared.
This could be further improved by by doing a one time allocation of an auxiliary array, aux = [none]*n, where n is the number of lines (main() would need to count lines and pass n as a parameter to the sort function). If using a top down merge sort, a pair of mutually recursive functions can be used to avoid copying of data (in this case, I assume the "data" is actually the equivalent of an array of pointers to strings, and that the strings are never moved by the sort). One function ends up with a sorted sub-array in the original array, the other function ends up with a sorted sub-array in the auxiliary array. Each function calls the other one twice, once for left half, once for right half, then merges the two halves. In the special case where the sorted data is to end up in the auxiliary array and a size of 1, a single element is copied from the original to the auxiliary array.
A bottom up merge sort would be a bit faster as it skips all of the recursion used to generate n-1 pairs of indices, and starts off by treating an array of n elements as n sub-arrays of 1 element each, then using iteration to manipulate the indices. It's not a lot faster because most of the time is spent in the merge function and the merge function is identical for both top down and bottom up merge sort. Similar to the optimized top down merge sort, copying is avoided by changing the direction of merge based on the merge pass. The number of merge passes is determined in advance based on n
, and if it would be an odd number of passes, the first pass can swap pairs of elements in place, leaving an even number of merge passes to do so the sorted data ends up in the original array.
It appears that this challenge was intended to be implemented in C, since it provides a C snippet. A python implementation will be significantly slower.