Python实现排序算法1
排序算法有很多种,下面列举几种:
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种算法在下一篇博客中
有问题欢迎大家给我留言
相关文章