Number of comparisons in insertion sort

后端 未结 2 1271
野性不改
野性不改 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:17

    Don't forget that loop header executed +1 more then the loop body, which we call the exit-condition, take this example:

    S = 0;
    for(int i = 0; i < 5; i++) {
        S++;
    }
    

    The S++ runs 5 times, however the i < 5 runs 6 times, the last one is to check if i < 5, will find the false and exit the loop.

提交回复
热议问题