Python使用二分插入排序竟然比直接插入排序快99倍!
之前发布同一个算法,C++竟然比C快8倍! , 有同学提出是因为C++中使用了二分插入排序,于是用python比较了下两种排序差距有多大。
测试结果如下:
Python insertion sort took time: 1:39:42.448904
Python insertion sort with binary search took time: 0:01:13.263267
代码如下:
import datetime import bisect def insertion_sort(l): for i in xrange(1, len(l)): j = i-1 key = l[i] while (l[j] > key) and (j >= 0): l[j+1] = l[j] j -= 1 l[j+1] = key def insertion_sort_bin(seq): for i in range(1, len(seq)): bisect.insort(seq, seq.pop(i), 0, i) a=[] for x in range(200000): a.append(x) a.reverse() start = datetime.datetime.now() insertion_sort(a) end = datetime.datetime.now() print "Python insertion sort took time: %s" % (end-start) a.reverse() start2 = datetime.datetime.now() insertion_sort_bin(a) end2 = datetime.datetime.now() print "Python insertion sort with binary search took time: %s" % (end2-start2)
同样是python,算法不一样,速度差百倍!