快速排序,是一个基于递归的算法,其核心思想如下:对于列表,选取一个轴值(一般选取第一个元素或者最后一个元素),把列表中小于该轴值的排在左边,大于该轴值的排在右边,这样,轴值在列表中的位置就确定了。由此衍生出了轴值的左子列表,以及右子列表,递归的对于左子列表以及右子列表使用上述的排序算法,直到子列表中只有一个元素。
def quikSort(nums): #基线条件:为空或只包含一个元素的数组是“有序”的 if len(nums) <= 1: return nums #递归条件,基准值 pivot = nums[0] #比基准值小的放在左边 less = [i for i in nums[1:] if i <= pivot] #比基准值大的放在右边 greater = [i for i in nums[1:] if i >= pivot] return quikSort(less) + [pivot] +quikSort(greater) if __name__=='__main__': print(quikSort([22,44,55,11,77,200,90]))