一、冒泡排序
def bubble_sort(ls):
length = len(ls)
# 比较趟数
for j in range(length):
# 每趟的比较次数
for i in range(j):
if ls[i] >= ls[i + 1]:
ls[i], ls[i + 1] = ls[i + 1], ls[i]
return ls
二、选择排序
def select_sort(ls):
length = len(ls)
for i in range(0, length-1):
smallest = i
for j in range(i+1, length):
if ls[j] < ls[smallest]:
ls[j], ls[smallest] = ls[smallest], ls[j]
return ls
三、快速排序
def partiton(ls, low, high):
key = ls[low]
while low < high:
while low < high and ls[high] >= key:
high -= 1
if low < high:
ls[low], ls[high] = ls[high], ls[low]
while low < high and ls[low] < key:
low += 1
if low < high:
ls[high], ls[low] = ls[low], ls[high]
return low
def quickSort(ls, low, high):
if low >= high:
return
center = partiton(ls, low, high)
quickSort(ls, low, center - 1)
quickSort(ls, center + 1, high)
return ls
网友评论