def quick_sort(list, i, j):
if i >= j:
return list
piovt = list[i]
low = i
high = j
while i < j:
# 从后往前找小于pivot的数,如果没找到, j--,如果找到,交换list[i] = list[j]
while i < j and list[j] >= piovt:
j -= 1
list[i] = list[j]
# 从前往后找大于pivot的数,如果没找到, i++,如果找到,交换list[j] = list[i]
while i < j and list[i] <= pivot:
i += 1
list[j] = list[i]
list[j] = piovt
quick_sort(list, low, i-1)
quick_sort(list,i+1, high)
return list
if __name__=="__main__":
lists=[30,24,5,58,18,36,12,42,39]
print("排序前的序列为:")
for i in lists:
print(i,end =" ")
print("排序后的序列为:")
for i in quick_sort(lists,0,len(lists)-1):
print(i,end=" ")
>>>
排序前的序列为:
30 24 5 58 18 36 12 42 39
排序后的序列为:
5 12 18 24 30 36 39 42 58
快速排序——python
最新推荐文章于 2024-08-15 01:55:01 发布