数据结构与算法五-快速排序(两个指针)

版权声明:版权归本人,仅供大家参考 https://blog.csdn.net/Dream____Fly/article/details/86655690

快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

def partition(list,first,last):
    primarykey = list[first]
    low = first + 1
    hight = last
    while hight > low:
        while low <= hight and list[low] <= primarykey:
            low += 1
        while low <= hight and list[hight] > primarykey:
            hight -= 1

        if hight > low:
            temp = list[hight]
            list[hight] = list[low]
            list[low] = temp

    while hight > first and list[hight] >= primarykey:
        hight -= 1

    if primarykey > list[hight]:
        list[first] = list[hight]
        list[hight] = primarykey
        return hight
    else:
        return first

def quicksort(list,first,last):
    if last > first:
        pkindex = partition(list,first,last)
        quicksort(list,first,pkindex -1 )
        quicksort(list,pkindex + 1,last)

def quick(list):
        quicksort(list,0,len(list) - 1)

def start_main():
    nums = [3,2,4,1,6,9,4]
    list = []
    quick(nums)
    for i in nums:
        list.append(i)
    print(list)

start_main()

猜你喜欢

转载自blog.csdn.net/Dream____Fly/article/details/86655690