[英]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.