簡體   English   中英

數組比較過多 - 就地快速排序

[英]Too many array comparisons - In-place quicksort

我實現了使用數組中間作為 pivot 的就地快速排序。 我有一些需要完成的測試用例,但是我的代碼似乎可以進行很多比較。 對於數組列表:

[10, 4, 33, 44, 17, 20, 3, 2, 9, 82, 38, 67, 55, 11, 32, 23, 19, 7, 6, 14, 29, 10, 10]

我應該得到 142 個比較,但我得到了 196 個。

這是我的代碼:

comparisons = 0

def addComparison() -> bool:
    global comparisons
    comparisons += 1
    return True

def quicksort(arr_list: list, lower_bound: int, upper_bound: int) -> list:
    if upper_bound > lower_bound:
        index = split_arr(arr_list, lower_bound, upper_bound)
        quicksort(arr_list, lower_bound, index)
        quicksort(arr_list, index+1, upper_bound)
    addComparison()

def split_arr(arr_list: list, lower_bound: int, upper_bound: int) -> int:
    global comparisons
    pivot_index = (lower_bound + upper_bound) // 2
    pivot_elem  = arr_list[pivot_index]

    while lower_bound <= upper_bound:

        left = lower_bound
        while addComparison() and arr_list[left] < pivot_elem:
            left += 1
        
        right = upper_bound
        while addComparison() and arr_list[right] > pivot_elem:
            right -= 1
        
        if left < right:
            arr_list[left], arr_list[right] = arr_list[right], arr_list[left]
            lower_bound = left  + 1
            upper_bound = right - 1
        else:
            return right
    return upper_bound

unsorted_list = [10, 4, 33, 44, 17, 20, 3, 2, 9, 82, 38, 67, 55, 11, 32, 23, 19, 7, 6, 14, 29, 10, 10]

quicksort(unsorted_list, 0, len(unsorted_list) - 1)

assert comparisons == 142

您實施的分區方案與您的講師不同,這將改變特定數據集的實際比較次數。

您的講師似乎已經實施了基本的“以最后一項為中心”分區方案——通過將中間項交換到最后一項進行了輕微修改,沒有比較。 我使用該算法在該數據集上得到 142。

使用https://en.wikipedia.org/wiki/Quicksort中的術語,您實現了 Hoare 分區方案,但您應該使用 Lomuto(可能在課堂上介紹過)。

我不想發太多,但如果我是對的,那么
您的代碼使用了 195 次比較和 29 次交換,並且
講師的代碼使用了 142 次比較和 87 次交換。

暫無
暫無

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

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