版权声明:本文为博主原创文章,转载请注明此文链接,谢谢了。个人技术博客:https://wardseptember.github.io/ https://blog.csdn.net/wardseptember/article/details/81451984
from __future__ import print_function
def gnome_sort(unsorted):
"""
地精排序,默认升序
算法思想:定义一个变量i,如果a[i-1]<=a[i],i=i+1,
否则,则交换,并把i变为i-1,就这样来回移动索引位置,
是整个列表有序
这个排序算法是稳定的
"""
if len(unsorted) <= 1:
return unsorted
i = 1
while i < len(unsorted):
if unsorted[i-1] <= unsorted[i]:
i += 1
else:
unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1]
i -= 1
if (i == 0):
i = 1
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(',')]
gnome_sort(unsorted)
print(unsorted)
一些说明:
- 我的github项目上有完整的算法代码,欢迎star,fork.
- 这里的所有算法均用python实现,“翻译”自国外某程序员的项目。
- 这里的“翻译”不单单指的是英译中,而且是为每个算法添加上算法思想描述和关键代码注释。
- 为什么要“翻译”这个项目?一方面是我想系统地学习下如何用python实现各种算法,另一方面是边学习边做笔记,通过这个项目记录自己的学习过程,再者,原项目经过“翻译”后,更容易被中国人理解,为想学习python的朋友提供一个不错的算法参考。
- 这里的算法很多,而且有些算法比较复杂,工作量很大。如果一些朋友有空闲时间,也可以参与翻译,十分欢迎。
- 另外我的个人博客网站也同步更新,更佳的阅读体验哦。