我正在尝试计算插入排序中进行的比较次数。目前,我的比较计数衡量的结果超出了应有的程度,我不确定为什么。
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]
会将比较数量多计算一次。
答案 0 :(得分:0)
如果position > 0
不正确,则不会对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)