在排序中,可能大家最先接触也最容易想到的应该是冒泡排序或者选择排序,然而在算法导论一书中却是从插入排序开始讨论,其实现思路类似于整理纸牌的过程。从一堆牌中选择第一张拿在手中,然后每拿一张牌均在手中找到这张牌应该放在的位置,这样当取完了全部的纸牌,手中的纸牌就是有序的了。
def insertion_sort(A):
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i>=0 and A[i]>key:
A[i+1] = A[i]
i = i - 1
A[i+1] = key
A = [5,2,4,6,1,3]
insertion_sort(A)
print(A)
运行结果:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
[1, 2, 3, 4, 5, 6]
>>>