您的位置:首页 > 编程语言 > Python开发

[硕.Love Python] InsertionSort(插入排序)

2017-02-13 08:24 411 查看
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直播间:http://www.panda.tv/671023
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  语言 编程 python