2016-05-14 10 views
1

2つのリストをマージし、ソートされたリストの合計を返す関数を作成しようとしています。2つのリストのPython挿入ソート

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 algoですが、2つのリストです。

+0

あなたは( 'ソート' BIFの知っている) ''、右? – LarsVegas

+0

@LarsVegas sure;) – Martin

+0

多分あなたは質問を再フレーズする必要があります – LarsVegas

答えて

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] 
0

コード内で自分自身を

def insertionSort(alist,blist): 

    return sorted(alist + blist) 

をソートすることになる最も明白な方法で動作しますが、あなただけのreturn文を追加するのを忘れ

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] 
+0

お返事ありがとうございます!しかし、私はこのようなことをしようとしています。http://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html – Martin

+0

またはhttp://www.geekviewpoint.com/python/sorting/insertionsort – Martin

+0

doesn戻り値 – Martin

関連する問題