排序算法有很多种,下面列举几种:
1.冒泡排序
2.选择排序
3.插入排序
4.希尔排序
5.快速排序
6.归并排序
1.冒泡排序
# -*- coding:utf-8 -*-
def bubble_sort(alist):
"""冒泡排序"""
for j in range(len(alist)-1):
for i in range(0,len(alist)-1-j):
if alist[i] > alist[i+1]:
alist[i],alist[i+1] = alist[i+1],alist[i]
print(alist)
if __name__ == "__main__":
a=[10,9,81,7,6,5,41,3,2,1]
bubble_sort(a)
# [1, 2, 3, 5, 6, 7, 9, 10, 41, 81]
2.选择排序
# -*- coding:utf-8 -*-
def selection_sort(alist):
"""选择排序"""
n = len(alist)
for i in range(n-1):
min = i
for j in range(i+1,n):
if alist[min] > alist[j]:
min = j
alist[i],alist[min] = alist[min],alist[i]
print(alist)
if __name__ == "__main__":
a = [6,86,3,5,0,43,90,100]
print(a)
selection_sort(a)
# [6, 86, 3, 5, 0, 43, 90, 100]
# [0, 3, 5, 6, 43, 86, 90, 100]
3.插入排序
def insert_sort(alist):
"""插入排序"""
for i in range(1,len(alist)):
j = i
while j > 0 :
if alist[j] < alist[j-1]:
alist[j-1],alist[j] = alist[j],alist[j-1]
j -= 1
else:
break
if __name__ == "__main__":
a = [6,86,3,5,0,43,90,100]
print(a)
insert_sort(a)
print(a)
# [6, 86, 3, 5, 0, 43, 90, 100]
# [0, 3, 5, 6, 43, 86, 90, 100]
剩下3种算法在下一篇博客中
有问题欢迎大家给我留言
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。