Python 计数交换和比较插入排序

Python 计数交换和比较插入排序,python,algorithm,sorting,insertion-sort,Python,Algorithm,Sorting,Insertion Sort,尝试在交换和比较上运行计数,但很简单:我不知道放在哪里,也不知道应该修改多少代码来获得计数 def insertionSort(alist): swap = 0 compare = 0 for index in range(1, len(alist)): currentvalue = alist[index] position = index while position > 0 and

尝试在交换和比较上运行计数,但很简单:我不知道放在哪里,也不知道应该修改多少代码来获得计数

def insertionSort(alist):
    swap = 0
    compare = 0
    for index in range(1, len(alist)):
        currentvalue = alist[index]        
        position = index        
        while position > 0 and alist[position - 1] > currentvalue:
             alist[position] = alist[position - 1]            
             position -= 1
             #I believe I would put compare += 1 here        
        alist[position] = currentvalue
        #And swap += 1 here, but I'm almost positive it wouldn't give me accurate readings.

   return swap, compare

我试图解决你的问题。我已经想出了一个解决办法


代码
样本IO 我已经根据一些示例输入和输出对它进行了测试。以下是其中的几个:

Input 1: [1, 2, 3]
Output : Swap: 0    Compare: 2

Input 2: [1, 3, 2]
Swap: 1 Compare: 2

Input 3: [3, 2, 1]
Output : Swap: 3    Compare: 3

如果您发现答案有任何错误,请发表评论

Input 1: [1, 2, 3]
Output : Swap: 0    Compare: 2

Input 2: [1, 3, 2]
Swap: 1 Compare: 2

Input 3: [3, 2, 1]
Output : Swap: 3    Compare: 3