Here’s my python implementation of merge sort:
def sort(lst):
if len(lst) < 2:
return lst
def merge(left, right):
i = j = 0
merged = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
return merged
middle = len(lst) / 2
return merge(sort(lst[:middle]), sort(lst[middle:]))
When I use it, however, this implementation only returns a list with a single item – the smallest item in the list.
For instance, sort([1,2,3]) returns [1], and sort([4,2,-1,5]) returns [-1].
Why? Thank you.
The problem is in the loop condition in
merge(). The loop stops once you’ve reached the end of either of the two lists, while you of course want all elements from both. If you try testing themerge()function in isolation, you can see how this causes problems:You need to ensure that once you’ve reached the end of one list that you still copy the remaining elements from the other one.
One way of doing this is to add another pair of loops which append any remaining elements from
leftorrighttomergedafter the main merge loop.