[硕.Love Python] InsertionSort(插入排序)
2017-02-13 08:21
337 查看
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://edu.csdn.net/combo/detail/174
《Python科学计算—NumPy实战课程》:
http://edu.51cto.com/course/course_id-5046.html
熊猫TV直播间:
http://www.panda.tv/671023
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://edu.csdn.net/combo/detail/174
《Python科学计算—NumPy实战课程》:
http://edu.51cto.com/course/course_id-5046.html
熊猫TV直播间:
http://www.panda.tv/671023
相关文章推荐
- [硕.Love Python] InsertionSort(插入排序)
- Python 数据结构与算法——插入排序(insertion sort)
- 插入排序(INSERTION-SORT) PYTHON实现
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- 经典排序算法 – 插入排序Insertion sort
- 插入排序(insertion sort)算法实现
- [算法练习]Insertion Sort 插入排序
- 插入排序(InsertionSort)
- Insertion Sort List 使用插入排序将链表排序
- 插入排序 insertion sort
- PHP Array -- PHP排序 -- 插入排序(Insertion Sort)
- python insertion sort
- 经典算法(8)- 插入排序(Insertion Sort) 及三个基本排序算法的比较
- 算法:冒泡排序(Bubble Sort)、插入排序(Insertion Sort)和选择排序(Selection Sort)总结
- 算法学习记录-排序——插入排序(Insertion Sort)
- 【LeetCode with Python】 Insertion Sort List
- 插入排序(1)InsertionSort
- insertion sort 插入排序
- 插入排序(insertion_sort)详解
- 插入排序 (Insertion Sort)