排序算法的Python实现

时间:2022-06-09 02:13:00

冒泡排序

def bubble_sort(l):
n = len(l)
for i in range(n):
for j in range(i+1, n):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
return l

插入排序

def insert_sort(l):
n = len(l)
for i in range(1, n):
key = l[i]
j = i-1
while j >= 0:
if l[j] > key:
l[j], l[j+1] = key, l[j]
j -= 1
return l

直接选择排序

def select_sort(l):
n = len(l)
for i in range(n):
min = i
for j in range(i+1, n):
if l[min] > l[j]:
min = j
l[min], l[i] = l[i], l[min]
return l

快速排序

def quick_sort(l, low, high):
i = low
j = high
if i >= j:
return l
key = l[i]
while i < j:
while i < j and l[j] >= key:#从右往左,找到小于key的j
j -= 1
l[i] = l[j]#交换l[i]和l[j]
while i < j and l[i] <= key:#从左往右,找到大于key的i
i += 1
l[j] = l[i]#交换l[j]和l[i]
l[i] = key#退出时,i==j;将key放在l[i]的位置
quick_sort(l, low, i-1)#调用递归
quick_sort(l, j+1, high)
return l