# 从小到大排序
# 冒泡排序
def bubble_sort(li):
for i in range(len(li)-1):
for j in range(len(li)-i-1):
if li[j] < li[j+1]:
li[j], li[j+1] = li[j+1], li[j]
# 选择排序
def select_sort_simple(li):
li_new = []
for i in range(len(li)):
min_val = max(li)
li_new.append(min_val)
li.remove(min_val)
return li_new
def select_sort(li):
for i in range(len(li)-1):
min_loc = i
for j in range(i+1, len(li)):
if li[j] < li[min_loc]:
li[j], li[min_loc] = li[min_loc], li[j]
# 插入排序
def insert_sort(li):
for i in range(1, len(li)):
temp = li[i]
j = i-1
while j >= 0 and li[j] > temp:
li[j+1] = li[j]
j -= 1
li[j+1] = temp
# 快速排序
def partition(li, left, right):
temp = li[left]
while left < right:
while li[right] >= temp and left < right:
right -= 1
li[left] = li[right]
while li[left] <= temp and left < right:
left += 1
li[right] = li[left]
li[left] = temp
return left
def quick_sort(li, left, right):
if left < right:
mid = partition(li, left, right)
quick_sort(li, left, mid)
quick_sort(li, mid+1, right)
li = [1, 5, 4, 2, 1, 9, 5, 4]
# bubble_sort(li)
# li = select_sort_simple(li)
# select_sort(li)
# insert_sort(li)
# quick_sort(li, 0, len(li)-1)
print(li)
Python的四种排序
于 2024-02-25 15:46:12 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)