- 冒泡排序
def bubble_sort(alist):
# 需操作 n-1 次
for i in range(len(alist)-1, 0, -1):
# 每次循环 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)
# 需要循环 n-1 次
for i in range(n-1):
# i位置默认最小值
min_index = i
# 从 i+1 位置循环到末尾找最小值
for j in range(i+1, 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 位置开始,循环到末尾
for i in range(1, n):
# 从当前位置往前查找小于它的数
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)