作为高效的排序算法,归并和快排常出现在面试中,让快速手写算法。
下面贴出python版本
#快速排序 分治和递归的思想 随机选一个基准点,比它小的放左边,比它大的放右边
def quickSort(nums:list,low,high):
if low >= high:
return
pivot = partition(nums,low,high)
quickSort(nums,low,pivot-1)
quickSort(nums,pivot+1,high)
def partition(nums,low,high):
index = random.randint(low,high)
#将随机选择的值与末尾值交换位置
nums[index],nums[high] = nums[high],nums[index]
i,j = low,low
while j<high:
if nums[j] < nums[high]:
nums[j],nums[i] = nums[i],nums[j]
i+=1
j+=1
#将末尾的随机值,放回中间位置,同时返回这个分隔点位置
nums[high],nums[i] = nums[i],nums[high]
return i
#快速排序 基本思想分治 随机选一个基准点,比它小的放左边,比它大的放右边
在这里插入代码片