- 冒泡排序
def bubble_sort(alist):
# 需操作 n-1 次
for i in range(len(alist)-1, 0, -1):
# 每次循環(huán) i 次
for j in range(i):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1], alist[j]
if __name__ == '__main__':
alist = [4, 1, 56, 34, 12, 18]
bubble_sort(alist)
print(alist)
- 選擇排序
def selection_sort(alist):
n = len(alist)
# 需要循環(huán) n-1 次
for i in range(n-1):
# i位置默認(rèn)最小值
min_index = i
# 從 i+1 位置循環(huán)到末尾找最小值
for j in range(i+1, n):
# 如果出現(xiàn)小于 i 位置值稻爬,則交換
if alist[j] < alist[i]:
min_index = j
alist[i], alist[j] = alist[j], alist[i]
if __name__ == '__main__':
alist = [12, 2, 34, 78, 6]
selection_sort(alist)
print(alist)
- 插入排序
def insert_sort(alist):
n = len(alist)
# 從 1 位置開始,循環(huán)到末尾
for i in range(1, n):
# 從當(dāng)前位置往前查找小于它的數(shù)
for j in range(i, 0, -1):
if alist[j] < alist[j-1]:
alist[j-1],alist[j] = alist[j], alist[j-1]
if __name__ == '__main__':
alist = [4, 8, 2, 1, 23, 15]
insert_sort(alist)
print(alist)