You don’t need to keep track of two lists. The following works fine:
def gensort(L):
if len(L) == 1:
return L
sorted_list = [min(L)]
L.remove(min(L))
return sorted_list + gensort(L)
Here’s what’s happening:
gensort([4, 1, 3, 2]) # returns [1] + gensort([4, 3, 2])
gensort([4, 3, 2]) # returns [2] + gensort([4, 3])
gensort([4, 3]) # returns [3] + gensort([4])
gensort([4]) # returns [4]
Substituting in the return values, you get:
[1] + [2] + [3] + [4]
Which evaluates to [1, 2, 3, 4]
.
CLICK HERE to find out more related problems solutions.