My implementation of merging two sorted lists in linear time - what could be improved?

后端 未结 9 545
忘掉有多难
忘掉有多难 2021-01-01 04:47

Fromg Google\'s Python Class:

E. Given two lists sorted in increasing order, create and return a merged
list of all the elements in sorted order. You may mod         


        
9条回答
  •  时光说笑
    2021-01-01 04:54

    I agree with other answers that extending and sorting is the most straightforward way, but if you must merge, this will be a little faster because it does not make two calls to len every iteration nor does it do a bounds check. The Python pattern, if you could call it that, is to avoid testing for a rare case and catch the exception instead.

    def linear_merge(list1, list2):
        merged_list = []
        i = 0
        j = 0
    
        try:
            while True:
                if list1[i] <= list2[j]:
                    merged_list.append(list1[i])
                    i += 1
                else:
                    merged_list.append(list2[j])
                    j += 1
        except IndexError:
            if i == len(list1):
                merged_list.extend(list2[j:])
            if j == len(list2):
                merged_list.extend(list1[i:])
        return merged_list
    

    edit Optimized per John Machin's comment. Moved try outside of while True and extended merged_list upon exception.

提交回复
热议问题