defpartion(li,left,right):
tem = li[left]# 选取一个临时值while left < right:while li[right]>= tem and left < right:# 从右选择小于tem的值
right -=1
li[left]= li[right]# 放置左侧指针位置while li[left]<= tem and left < right:# 从左侧选择大于tem的值
left +=1
li[right]= li[left]# 放置右侧指针的位置
li[left]= tem
return left
defQuick_sort(li,left,right):if left < right:
mid = partion(li,left,right)
Quick_sort(li,left,mid-1)
Quick_sort(li,mid+1,right)
li =[5,3,6,8,2,9,4,1,7]
Quick_sort(li,0,len(li)-1)print(li)# result[1,2,3,4,5,6,7,8,9]
时间复杂度对比
# 计算时间(函数)import time
defcal_time(func):defwarpper(*args,**kwargs):
t1 = time.time()
result = func(*args,**kwargs)
t2 = time.time()print("%s running time: %f secs."%(func.__name__, t2-t1))return result
return warpper