快速排序,需要注意第一个left>right 为跳出条件,不是right>left。同时在递归的时候需要剔除掉中间排好的值,left lo-1 lo+1 right 否则会递归深度太大。
class Solution:
def MySort(self , arr ):
# write code here
def quick_sort(left,right,arr):
if left>right:
return
target=arr[left]
lo=left
hi=right
while lo<hi:
while arr[hi]>target and lo<hi:
hi-=1
while arr[lo]<=target and lo<hi:
lo+=1
arr[lo],arr[hi]=arr[hi],arr[lo]
arr[lo],arr[left]=arr[left],arr[lo]
quick_sort(left,lo-1,arr)
quick_sort(hi+1,right,arr)
return arr
if len(arr)==0:
return arr
return quick_sort(0,len(arr)-1,arr)
京公网安备 11010502036488号