【算法图解】——快速排序改进

快速排序

思路
  • 如果列表为空或者只有一个元素则不用排序
  • 选择首元素为基准值
  • 创建两个列表:小于基准值的less=[ ]和大于基准值的high=[ ]
  • 遍历整个列表,小于基准值的放入less,大于基准值的放入high
注意!!!!!

列表循环的时候会出现和基准值相等的元素,放在哪边都可以,但是注意不要将基准值再遍历,这样就会导致每一次less的遍历都是以这个最开始的基准值为基准值并且less不会改变,进入死循环,故从下标为1的元素开始遍历

 for i in range(1, len(alist)) # 要从1开始遍历:
错误代码
def quicksort(alist):
    if len(alist) < 2:
        return alist
    else:
        pivot = 0 # 基准值下标
        less = []
        high = []
        
        for i in range(len(alist)):
            if alist[i] <= alist[pivot]:
                less.append(alist[i])
            else:
                high.append(alist[i])
        
        return quicksort(less) + [alist[pivot]] + quicksort(high)

array = [5, 32, 15, 47, 85, 12, 16, 17 , 3]
print(quicksort(array))
RecursionError: maximum recursion depth exceeded in comparison

递归迭代深度超过了python的默认

正确代码
def quicksort(alist):
    if len(alist) < 2:
        return alist
    else:
        pivot = 0 # 基准值下标
        less = []
        high = []
        
        for i in range(1, len(alist)):
            if alist[i] <= alist[pivot]:
                less.append(alist[i])
            else:
                high.append(alist[i])
        
        return quicksort(less) + [alist[pivot]] + quicksort(high)

array = [5, 32, 15, 47, 85, 12, 16, 17 , 3]
print(quicksort(array))

[3, 5, 12, 15, 16, 17, 32, 47, 85]

代码优化
def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0] # 基准值
        
        less = [i for i in array[1:] if i <= pivot] # 小于基准值的列表
        greater = [i for i in array[1:] if i > pivot] # 由大于基准值组成的列表
        
        return quicksort(less) + [pivot] + quicksort(greater)

array = [5, 32, 15, 47, 85, 12, 16, 17 , 3]
print(quicksort(array))

[3, 5, 12, 15, 16, 17, 32, 47, 85]

发布了165 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44478378/article/details/104413016