数据结构day1:排序

时间:2022-10-20 04:15:02

1,冒泡排序算法的python实现

def bubble_sort(alist):
pass
count = len(alist)-1
for index in range(count,0,-1):
for new_index in range(index):
if alist[new_index] > alist[new_index + 1]:
alist[new_index],alist[new_index+1] = alist[new_index+1],alist[new_index] return alist li = [9,3,5,7,11,34,88,45,32]
print(bubble_sort(li))

2,快速排序算法的python实现

def quick_sort(alist,left,right):
if left >= right:
return alist
low = left
high = right
key = alist[low] while low < high:
# 先从右向左
if low < high and alist[high] >= key:
high -= 1
alist[low] = alist[high] # 再从左到右
if low < high and alist[low] <= key:
low += 1
alist[high] = alist[low] alist[high] = key quick_sort(alist,left,low-1)
quick_sort(alist,low+1,right)
return alist # 不要少了这一句 li = [9,3,5,7,11,34,88,45,32]
print(quick_sort(li,0,8))