Python 插入排序

Document 對象參考手冊 Python3 實例

插入排序(英語:Insertion Sort)是一種簡單直觀的排序演算法。它的工作原理是通過構建有序序列,對於未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入。

實例

def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key arr = [12, 11, 13, 5, 6] insertionSort(arr) print ("排序後的數組:") for i in range(len(arr)): print ("%d" %arr[i])

執行以上代碼輸出結果為:

排序後的數組:
5
6
11
12
13

Document 對象參考手冊 Python3 實例