【问题标题】:How to count the amount of swaps made in insertion sort?如何计算插入排序中的交换量?
【发布时间】:2019-05-17 05:55:53
【问题描述】:

我正在尝试计算插入排序进行交换或对数组中的值进行排序的次数。我应该在哪里增加交换计数?

这是在 Python 3 上的,我已经测试了几个缩进,但似乎都没有工作。此外,无济于事,我在各种网站上寻找答案,包括堆栈溢出。

def insertionsort(array):
    swapsmade = 0
    checksmade = 0
    for f in range(len(array)):
        value = array[f]
        valueindex = f
        checksmade += 1
        # moving the value
        while valueindex > 0 and value < array[valueindex-1]:
            array[valueindex] = array[valueindex-1]
            valueindex -= 1
            checksmade += 1
        swapsmade += 1 #  FIX THIS
        array[valueindex] = value
    print(array)
    swapsnchecks = "{} swaps were made. {} checks were made.".format(swapsmade, checksmade)
    return swapsnchecks

当我使用具有例如十个整数(即[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])的排序列表时,就会出现我如何放置计数器的问题。我预计输出为0 swaps were made. 55 checks were made.,但输出最终为10 swaps were made. 55 checks were made.

【问题讨论】:

  • 根据您给定的输入,0 swaps were made. 55 checks were made. 不正确。它应该是 0 次交换,10 次检查。如果您得到 10、55,那么您很可能将列表向后插入,在这种情况下 45,55 是正确的。当然,关于缩进,下面的答案也是正确的。

标签: python insertion-sort


【解决方案1】:

您只需要在 while 循环中缩进您的计数器,如下所示:

def insertionsort(array):
    swapsmade = 0
    checksmade = 0
    for f in range(len(array)):
        value = array[f]
        valueindex = f
        checksmade += 1
        # moving the value
        while valueindex > 0 and value < array[valueindex-1]:
            array[valueindex] = array[valueindex-1]
            valueindex -= 1
            checksmade += 1
            swapsmade += 1 #  Move inside the while loop
        array[valueindex] = value
    print(array)
    swapsnchecks = "{} swaps were made. {} checks were made.".format(swapsmade, checksmade)
    return swapsnchecks

例如:

print(insertionsort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(insertionsort([2, 1, 3, 4, 5, 6, 7, 8, 9, 10]))
print(insertionsort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 swaps were made. 10 checks were made.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 swaps were made. 11 checks were made
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
45 swaps were made. 55 checks were made.

【讨论】:

  • 想通了。 OP 正在向后输入列表,因此 10 次交换和 55 次检查是正确的......
  • 从头开始,45 次交换!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
相关资源
最近更新 更多