簡體   English   中英

使用quicksort(Python)查找第k個最小項目

[英]Finding the k-th smallest item with quicksort (Python)

我正在嘗試實現此視頻以及本文檔中討論的算法。

我的快速排序代碼依賴於選擇數組中的中間元素作為樞軸(請參見下文),與上面文檔的作者所使用的方法相反,該方法使用數組中的第一個元素作為樞軸,如此處所示在視頻中

顯然,我的代碼不起作用(最終超出了遞歸限制)。 我想知道這是因為我的代碼中出現了一些愚蠢的錯誤,還是只要我從中間選擇了樞軸,它就根本無法工作。

def partition(a, start, end):
    # I pick the pivot as the middle item in the array
    # but the algorithm shown in the video seems to
    # pick the first element in the array as pivot
    piv = (start + end) // 2
    pivotVal = a[piv]

    left = start
    right = end

    while left <= right:

        while a[left] < pivotVal:
            left += 1

        while a[right] > pivotVal:
            right -= 1

        if left <= right:
            temp = a[left]
            a[left] = a[right]
            a[right] = temp
            left += 1
            right -= 1

    return left


def quicksort(a, start, end, k):

    if start < end:
        piv = partition(a, start, end)

        if piv == (k - 1):
            print("Found kth smallest: " + piv)
            return a[piv]
        elif piv > (k - 1):
            return quicksort(a, start, piv, k)
        else:
            return quicksort(a, piv + 1, end, k)

myList = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quicksort(myList, 0, len(myList) - 1, 3)
print(myList)

如果使用包容數組邊界(這不是最方便的技巧),則必須將遞歸調用中的范圍更改為[start, piv - 1][piv + 1, end]

原因是,您要在數組左側的每個遞歸中重新考慮piv元素。

具有上述更改的代碼運行無任何堆棧溢出錯誤。

編輯對於k的幾個值,輸出不正確。 您可能需要再次檢查分區邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM