一.选择排序
dict1 = [2, 5, 1, 4, 9]
for i in range(0, len(dict1)):
for j in range(i + 1, len(dict1)):
if dict1[i] >= dict1[j]:
dict1[i], dict1[j] = dict1[j], dict1[i]
print(dict1)
运行结果:
二.冒泡排序
dict1 = [2, 5, 1, 4, 9]
for i in range(0, len(dict1)-1):
for j in range(0, len(dict1)-1-i):
if dict1[j] >= dict1[j+1]:
dict1[j], dict1[j+1] = dict1[j+1], dict1[j]
print(dict1)
运行结果:
三.插入排序
dict1 = [2, 5, 1, 4, 9]
for i in range(1, len(dict1)):
for j in range(i, 0, -1):
if dict1[j] <= dict1[j-1]:
dict1[j], dict1[j-1] = dict1[j-1], dict1[j]
print(dict1)
运行结果:
四.计数排序(桶排序)
arr = [7, 3, 2, 6, 1, 4, 9, 7]
max_num = arr[0]
min_num = arr[0]
for num in arr:
if num > max_num:
max_num = num
elif num < min_num:
min_num = num
#计数列表的长度
len_arr1 = max_num - min_num +1
#偏移量
offset = min_num
#初始化计数列表 元素全为0
arr1 = [0] * len_arr1
#排序后的列表
arr2 = [0] * len(arr)
#计数
for num in arr:
print(num)
arr1[num - offset] += 1
print(arr1)
index = 0
for i in range(0, len_arr1):
for j in range(0, arr1[i]):
print(i + offset, end=' ')
arr2[index] = i + offset
index += 1
print()
print(arr2)
运行结果(有过程):