【发布时间】: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