python---快速排序的实现

def quick_sort(alist, start, end):
    """快速排序"""

    # 递归退出
    if start >= end:
        return

    # 基准元素
    mid_value = alist[start]
    low = start
    high = end

    while low < high:
        # 移动时low和high都会改变, 下边的low<high不重复
        # high 左移
        while low < high and alist[high] >= mid_value:
            high -= 1
        alist[low] = alist[high]

        # low 右移
        while low < high and alist[low] < mid_value:
            low += 1
        alist[high] = alist[low]

    # low与high重合时, 退出循环, 即找到了基准元素的位置
    alist[low] = mid_value

    # 对基准元素左侧进行快速排序
    quick_sort(alist, start, low - 1)

    # 对基准元素右侧进行快速排序
    quick_sort(alist, low + 1, end)


if __name__ == '__main__':
    alist = [54, 93, 77, 31, 44, 55, 226, 20]
    quick_sort(alist, 0, len(alist)-1)
    print(alist)

posted @ 2020-03-18 15:28  凯旋.Lau  阅读(144)  评论(0编辑  收藏  举报