快速排序python递归实现

快速排序python递归实现

# 快速排序python
def swap(list,i,j):
    """位置互换"""
    list[i], list[j] = list[j], list[i]
    return list

def QuickSort(list, start, end):
    if start < end:
        i,j = start,end
        base = list[i] # 设置基数
        while i < j:
            while i < j and list[j] >= base: # 从后往前找
                j -= 1
                
            swap(list,i,j) # 当找到比基数小的数与其互换位置

            while i < j and list[i] <= base: # 从前往后找
                i += 1

            swap(list, i, j) # 当找到比基数大的数与其互换位置
        
        # 递归
        QuickSort(list,start,i-1) 
        QuickSort(list,j+1,end)
        return list

list = [56,34,78,56,98,86,45,56,32,89,99,46,33,87,56]
res = QuickSort(list,0,len(list)-1)
print(res)

输出结果

/usr/bin/python3.5 /home/python/Desktop/test/快速排序.py
[32, 33, 34, 45, 46, 56, 56, 56, 56, 78, 86, 87, 89, 98, 99]

Process finished with exit code 0

你可能感兴趣的:(算法)