Я пытаюсь подсчитать количество сравнений, выполненных в сортировке вставки. В настоящее время мой счетчик сравнения измеряет больше, чем должен, и я не уверен, почему.
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]
пересчитает количество сравнений на единицу.