Python version merges two sorted arrays into one sorted array

The first idea is to combine the two arrays into one array and then sort them. The problem returns to bubbling and quick sorting, and the ordering of the two arrays is not used. (not good)

The second idea is to compare the size of the head elements of the two ordered arrays in a loop, put the head elements into the new array, and delete them from the old array until one of the arrays has a length of 0. Then add the rest of the non-empty old array to the end of the new array. (Okay)

The sorting algorithm and test code of the second idea are as follows:

def merge_sort(a, b):
    ret = []
    while len(a)>0 and len(b)>0:
        if a[0] <= b[0]:
            ret.append(a[0])
            a.remove(a[0])    
        if a[0] >= b[0]:
            ret.append(b[0])
            b.remove(b[0])
    if len(a) == 0:
        ret += b
    if len(b) == 0:
        ret + = a
     return ret


if __name__ == '__main__':
    a = [1,3,4,6,7,78,97,190]
    b = [2,5,6,8,10,12,14,16,18]
    print(merge_sort(a, b))

 

 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325148799&siteId=291194637