欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

随机快排

程序员文章站 2024-03-25 13:21:58
...
import random
def quicksort(arr, L, R):
    if(L < R):
        swap(arr,L + int(random.random()*(R-L+1)), R)
        low,high=partition(arr, L, R)
        quicksort(arr, L ,low)
        quicksort(arr, high, R)
def partition(arr, L, R):
        less = L -1
        more = R
        while(L < more):
            if arr[L] < arr[R]:
                less += 1
                swap(arr, L,less)
                L += 1
            elif arr[L] > arr[R]:
                more -= 1
                swap(arr, L, more)
            else:
                L+=1
        swap(arr, more,  R)
        return less,more+1
def swap(arr, i, j):
    arr[i],arr[j]=arr[j],arr[i]
lst = [22,312,22,5,23,7,22]
quicksort(lst,0,6)
print(lst)
相关标签: 快排