两个列表的Python插入排序

时间:2016-05-14 19:09:02

标签: python sorting time-complexity

我试图创建一个合并2个列表并返回总排序列表的函数。

def insertionSort(alist,blist):

total = alist + blist

for index in range(1,len(total)):
    currentvalue = total[index]
    position = index

    while position>0 and total[position-1]>currentvalue:
        total[position]=total[position-1]
        position = position-1

        total[position]=currentvalue
        print(total)       

它有效,但它给我输出这样的东西:

>>> insertionSort([9,8,7], [5,4,3])

[8, 9, 7, 5, 4, 3]
[8, 7, 9, 5, 4, 3]
[7, 8, 9, 5, 4, 3]
[7, 8, 5, 9, 4, 3]
[7, 5, 8, 9, 4, 3]
[5, 7, 8, 9, 4, 3]
[5, 7, 8, 4, 9, 3]
[5, 7, 4, 8, 9, 3]
[5, 4, 7, 8, 9, 3]
[4, 5, 7, 8, 9, 3]
[4, 5, 7, 8, 3, 9]
[4, 5, 7, 3, 8, 9]
[4, 5, 3, 7, 8, 9]
[4, 3, 5, 7, 8, 9]
[3, 4, 5, 7, 8, 9]

但我只想要最后一行(结果)。我该怎么办?

另外,如果两个列表都没有排序,我很好奇这个函数的复杂性。这是o((alist+blist)^2)吗?

警告:我知道如何使用list.sort()。这个问题是this算法,但有2个列表。

2 个答案:

答案 0 :(得分:1)

您可以合并两个列表,例如

   l1 = [10,5,33] and 
   l2 = [36, 12,9]

   newl = l1.extend(l2)

   Output: [10, 5, 33, 36, 12, 9]

然后做:

    newl.sort()

    Output: [5, 9, 10, 12, 33, 36]

答案 1 :(得分:0)

最明显的方式是

def insertionSort(alist,blist):

    return sorted(alist + blist)

您的代码中的排序本身有效,您只是忘了添加一个返回语句

def insertionSort(alist,blist):

    total = alist + blist

    for index in range(1,len(total)):
        currentvalue = total[index]
        position = index

        while position>0 and total[position-1]>currentvalue:
            total[position]=total[position-1]
            position = position-1

            total[position]=currentvalue
    print(total)
    return total 

演示:

a = [3, 2, 88, 99]
b = [9, 5]
def insertionSort(alist, blist):

    total = alist + blist

    for index in range(1,len(total)):
        currentvalue = total[index]
        position = index

        while position>0 and total[position-1]>currentvalue:
            total[position]=total[position-1]
            position = position-1

            total[position]=currentvalue
    print(total)
    return total

In [18]: insertionSort(a,b)
[2, 3, 5, 9, 88, 99]
Out[18]: [2, 3, 5, 9, 88, 99]