Merge and sort a list using merge sort

This is my code.

def merge_lists(all_lst):
    if len(all_lst) < 2:
        return all_lst[0]   # get rid of the extra [] 
    left = merge_lists(all_lst[:len(all_lst)//2]) #[[2, 7, 10]]  ##[[0, 4, 6]]      
    right = merge_lists(all_lst[len(all_lst)//2:])#[[0, 4, 6], [3, 11]] ##[[3,11]]
    def merge(left,right):
        results = []
        while left and right:
            if left[0] < right[0]:
                results.append(left[0])
                left.remove(left[0])
            else:
                results.append(right[0])
                right.remove(right[0])
        results.extend(left)
        results.extend(right)
        return results
    return merge(left, right) 

I can get an answer when I put this

all_lst = [[2, 7, 10], [0, 4, 6], [3, 11]]
print(merge_lists(all_lst)) # [0, 2, 3, 4, 6, 7, 10, 11]

But when I tried to change it a little, it no longer works

 all_lst = [[2, 7, 10], [0, 4, 6], [3, 11, 1]]
print(merge_lists(all_lst)) ##[0, 2, 3, 4, 6, 7, 10, 11, 1]

Can i find out what's wrong

+4
source share
1 answer

The third list is not sorted. When you make your final extension, 1 is inserted at the end of the final list. You must sort your lists before calling merge.

In other words, your entry should be:

 all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]

These merging methods consist in assuming that the signatures are streamlined.

For example, take these two lists:

left = [1, 3]
right = [2, 4]
results = []    

The merger is as follows:

if left[0] < right[0]:
    results.append(left[0])
    left.remove(left[0])

so now

results = [1]
left = [3]
right = [2,4]

but if you have:

left = [3, 1]
right = [2, 4]
results = []   

The merger is as follows:

if left[0] < right[0]: #false
else:
    results.append(right[0])
    right.remove(right[0])

so now

results = [2]
left = [3,1]
right = [4]

.

0

Source: https://habr.com/ru/post/1532030/


All Articles