快速排序
分析:选择锚点,一次分成两部分,之后对剩下的子序列做同样的操作
# quick sort
def partition(nums,start,end): # attention the small position and end position
if start>end:
return
small = start-1
for index in range(start,end):
if nums[index]<nums[end]:
small+=1
# if small!=index:
nums[index],nums[small]=nums[small],nums[index]
small+=1
nums[small],nums[end] = nums[end],nums[small]
length = end-small+1
return small,length # the pivot's position, the right part length
def quicksort(nums,start,end):
if (start==end):
return
index,length = partition(nums,start,end)
if index>start:
quicksort(nums,start,index-1)
if index<end:
quicksort(nums,index+1,end)
nums = [4,6,2,6,8,4,3,8,2,56,97,35,43,64,23,65,734,436,24]
quicksort(nums,0,len(nums)-1)
print(nums)