Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 演算法之插入排序

初學 Python,寫一些演算法來練練手。程式以輸入 'e' 作為結束。

Python 插入排序程式碼如下:

def insert_sort(seq):
    length = len(seq)
    for i in range(1,length):
        temp = seq[i]
        for j in range(i-1, -1, -1):
            if temp < seq[j]:
                seq[j+1]=seq[j]      
            else:
                j+=1
                break
        if seq[j] is not temp:
            seq[j]=temp
           
def do_test():
    seq = []
    print('Please input the sequence:')
    while True:
        ch = input()
        if ch is 'e':
            break
        seq.append(int(ch)) 
    insert_sort(seq)
    print('After the insertSort:')
    print(seq)

if __name__ == '__main__':
    do_test()

插入排序的核心思路是:把陣列分成已排序與未排序兩部分,每次取未排序部分的下一個元素,往前比較並插入到已排序部分的合適位置,直到全部元素都排好序為止。

Copyright © Linux教程網 All Rights Reserved