冒泡排序
def bubble_sort():
# find the max number
numbers = [4, 3, 5, 12, 4, 9, 6, 7]
for i in range(len(numbers)-1, 0, -1):
for j in range(i):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
print(numbers)
选择排序
def select_sort():
# find the minimum
numbers = [4, 3, 5, 12, 4, 9, 6, 7]
for i in range(len(numbers)-1):
for j in range(i+1, len(numbers)):
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
print(numbers)
插入排序
def insert_sort():
numbers = [4, 3, 5, 12, 4, 9]
# 保证0~i有序
for i in range(1, len(numbers)):
for j in range(i, 0, -1):
if numbers[j] >= numbers[j - 1]:
break
else:
numbers[j - 1], numbers[j] = numbers[j], numbers[j - 1]
print(numbers)