1. 程式人生 > >演算法導論—插入排序python實現

演算法導論—插入排序python實現

 Insertion sort works the way many people sort a hand of playing cards.

打撲克牌摸牌—排牌,這就是插入排序的原理

I think it's the hardest thing to deal with the boundary question, what initial value of j is the key problem.

最難解決的就是邊界問題了, j 取什麼樣的初值是關鍵性的問題

# 插入排序-升序
def insert_sort(arr):
    length = len(arr)
    for i in range(1, length):
        key = arr[i]
        for j in range(i, -1, -1):
            if key < arr[j - 1]:
                arr[j] = arr[j - 1]
            else:
                break
        arr[j] = key


array = [5, 2, 4, 6, 1, 3]
insert_sort(array)
print(array)