版权声明:本文为博主原创文章,转载请注明此文链接,谢谢了。个人技术博客:https://wardseptember.github.io/ https://blog.csdn.net/wardseptember/article/details/81516360
from __future__ import print_function
def insertion_sort(collection):
"""
插入排序
算法思想:
初始时,只考虑数组下标0处的元素,只有一个元素,显然是有序的。
然后第一趟 对下标 1 处的元素进行排序,保证数组[0,1]上的元素有序;
第二趟 对下标 2 处的元素进行排序,保证数组[0,2]上的元素有序;
.....
.....
第N-1趟对下标 N-1 处的元素进行排序,保证数组[0,N-1]上的元素有序,也就是整个数组有序了。
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([])
[]
>>> insertion_sort([-2, -5, -45])
[-45, -5, -2]
"""
for index in range(1, len(collection)):
while 0 < index and collection[index] < collection[index - 1]:
collection[index], collection[
index - 1] = collection[index - 1], collection[index]
index -= 1
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = raw_input('输入待排序的数,用\",\"分隔:\n').strip()
#strip() 方法用于移除字符串头尾指定的字符(默认为空格)
unsorted = [int(item) for item in user_input.split(',')]
print(insertion_sort(unsorted))
一些说明:
- 我的github项目上有完整的算法代码,欢迎star,fork.
- 这里的所有算法均用python实现,“翻译”自国外某程序员的项目。
- 这里的“翻译”不单单指的是英译中,而且是为每个算法添加上算法思想描述和关键代码注释。
- 为什么要“翻译”这个项目?一方面是我想系统地学习下如何用python实现各种算法,另一方面是边学习边做笔记,通过这个项目记录自己的学习过程,再者,原项目经过“翻译”后,更容易被中国人理解,为想学习python的朋友提供一个不错的算法参考。
- 这里的算法很多,而且有些算法比较复杂,工作量很大。如果一些朋友有空闲时间,也可以参与翻译,十分欢迎。
- 另外我的个人博客网站也同步更新,更佳的阅读体验哦。