簡體   English   中英

為什么我過度計算此插入排序算法中的比較量?

[英]Why am I over counting the amount of comparisons in this insertion sort algorithm?

我試圖計算插入排序中的比較次數。 目前我的比較計數超出應有的水平,我不知道為什么。

def compare(data, a, b):
    """Returns True if element at index a > element at index b"""
    return data[a] > data[b]

def swap(data, a, b):
    """Swaps the element at index a with element at index b"""
    data[a], data[b] = data[b], data[a]

def insertion_sort(data):
    """Sorts the list into ascending order"""
    comparison_count = 0
    swap_count = 0
    for index in range(1, len(data)):
        position = index
        while position > 0 and compare(data, position - 1, position):
            comparison_count += 1
            swap(data, position - 1, position)
            swap_count += 1
            position -= 1
        comparison_count += 1
    print('Length:', len(data), 'Comparisons:', comparison_count, 'Swaps:', swap_count)

例如,對列表進行排序

[50, 63, 11, 79, 22, 70, 65, 39, 97, 48]

將超過一個比較數量。

如果position > 0不為true,則不評估compare(data, position - 1, position) ,但無論如何都要使用comparison_count += 1跟進。

一種直接的方法來修復它並組合增量(以整體更優雅的循環為代價)是:

while position > 0:
    comparison_count += 1

    if not compare(data, position - 1, position):
        break

    swap(data, position - 1, position)
    swap_count += 1
    position -= 1

這也相當於

for index in range(1, len(data)):
    for position in range(index, 0, -1):
        comparison_count += 1
        if not compare(data, position - 1, position):
            break

        swap_count += 1
        swap(data, position - 1, position)

暫無
暫無

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

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