def insertionSort(a): for i in xrange(1, len(a)): t = a[i] for j in xrange(i, 0, -1): if a[j-1] <= t: break a[j] = a[j-1] else: j = 0 a[j] = t def binaryInsertionSort(a): for i in xrange(1, len(a)): l, r, t = 0, i - 1, a[i] while l <= r: m = (l + r) / 2 if t < a[m]: r = m - 1 else: l = m + 1 for j in xrange(i - 1, l - 1, -1): a[j+1] = a[j] a[l] = t if __name__ == ‘__main__‘: from random import shuffle data = range(100) shuffle(data) print data insertionSort(data) print data shuffle(data) print data binaryInsertionSort(data) print data
刘硕老师Python精品课程:
《Python高级编程技巧实战》:
http://coding.imooc.com/class/62.html
《Python算法实战视频课程》:
http://study.163.com/course/courseMain.htm?courseId=1003617013
《Python科学计算—NumPy实战课程》:
http://edu.51cto.com/course/course_id-5046.html
熊猫TV直播间:
[硕.Love Python] InsertionSort(插入排序)
原文:http://liushuo777.blog.51cto.com/10091950/1897167