Python實現排序算法1
阿新 • • 發佈:2019-05-15
print ali def 冒泡 pytho 歸並排序 sel 問題 __name__ 排序算法有很多種,下面列舉幾種:
1.冒泡排序
2.選擇排序
3.插入排序
4.希爾排序
5.快速排序
6.歸並排序
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種算法在下一篇博客中
有問題歡迎大家給我留言
Python實現排序算法1