Number of comparisons in insertion sort

后端 未结 2 1307
野性不改
野性不改 2021-01-27 05:29

In this program, I want to calculate the number of data comparisons in the insertion sort, but my code is not working as I expected.

def insertionSort(list):
            


        
2条回答
  •  不知归路
    2021-01-27 06:06

    the problem is

    if value >= list[j]:
         numOfComp += 1
         j = j - 1
    

    If value >= list[j] you can and should simply exit your while loop and stop further comarisons

    Also you are repeating the comparisons twice See the following refined code

    def insertionSort(list):
        numOfComp = 0
        for i in range(1,len(list)):
            value = list[i]
            j = i - 1
            while j>=0:
                if value

提交回复
热议问题