代码改变世界

Algorithm - Quick sort

2021-06-23 16:41  WayneWei  阅读(31)  评论(0编辑  收藏  举报

Algorithm implementation Quick sort:

# Quick sort

mylist = [3, 6, 9, 2, 5, 8, 1, 4, 7]

def quicksort(list, start, end):
    if start > end:
        return

    pivot = list[start]
    left = start
    right = end

    while left < right:
        while left < right and list[right] > pivot:
            right -= 1
        list[left] = list[right]

        while left < right and list[left] < pivot:
            left += 1
        list[right] = list[left]

    list[left] = pivot
    quicksort(list, start, left-1)
    quicksort(list, left+1, end)

quicksort(mylist, 0, len(mylist)-1)
print(mylist)

Testing output:

D:\test\venv\Scripts\python.exe D:/test/algorithm.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Process finished with exit code 0