So I'm trying to understand this simple merge and sort algorithm in python. Here's the code:
def merge(left, right, lt):
"""Assumes left and right are sorted lists.
lt defines an ordering on the elements of the lists.
Returns a new sorted(by lt) list containing the same elements
as (left + right) would contain.
"""
result = []
i,j = 0, 0
while i < len(left) and j < len(right):
if lt(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
def sort(L, lt = lambda x,y: x < y):
"""Returns a new sorted list containing the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = int(len(L)/2)
left = sort(L[:middle], lt)
right = sort(L[middle:], lt)
print left, right
return merge(left, right, lt)
I get what it's trying to do, and I understand all of the code in the merge function and have a basic understanding of the sort function.
What I don't understand is how the "else" portion of the sort function actually works. It seems like it keeps recursively calling the sort function to assign smaller and smaller split lists to the left and right variables. But since it is assigning new lists to "left" and "right" on every call to the recursive function, won't the end result just be the smallest versions of left and right?
How does the merge function, which seems to lie outside of the recursion, know that it needs to merge every single split list created?
