[英]How do I add a swap and comparisons counter in my code?
For a list of numbers, I am trying to sort them in ascending order.对于数字列表,我正在尝试按升序对它们进行排序。 At the same time, I need to add a swap and comparison counter to my output.同时,我需要在我的 output 中添加一个交换和比较计数器。 For the most part, how do I add the incrementation in my code?在大多数情况下,如何在我的代码中添加增量? My code:我的代码:
def insertion_sort(numbers):
"""Sort the list numbers using insertion sort"""
# TODO: Count comparisons and swaps. Output the array at the end of each iteration.
for i in range(1, len(numbers)):
j = i
# Insert numbers[i] into sorted part
# stopping once numbers[i] is in correct position
while j > 0 and numbers[j] < numbers[j - 1]:
swap(numbers, j, j - 1)
j -= 1
This is an insertion sorting method.这是一种插入排序方法。
Split up the condition so you can separate the comparisons from the swaps.拆分条件,以便您可以将比较与交换分开。
def insertion_sort(numbers):
"""Sort the list numbers using insertion sort"""
comparisons = 0
swaps = 0
for i in range(1, len(numbers)):
j = i
# Insert numbers[i] into sorted part
# stopping once numbers[i] is in correct position
while j > 0:
comparisons += 1
if numbers[j] < numbers[j - 1]:
swap(numbers, j, j - 1)
swaps += 1
else:
break
j -= 1
print(f'Comparisons: {comparisons}, Swaps: {swaps}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.