How does Python insertion sort work?

前端 未结 21 1681
南方客
南方客 2020-12-10 02:54

Here\'s a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don\'t know what to do, h

21条回答
  •  春和景丽
    2020-12-10 03:38

    Consider [3, 2, 1]

    The loop starts with 3. Since it is the first item in the list there is nothing else to do.

    [3, 2, 1]
    

    The next item is 2. It compares 2 to 3 and since 2 is less than 3 it swaps them, first putting 3 in the second position and then placing 2 in the first position.

    [2, 3, 1]
    

    The last item is 1. Since 1 is less than 3 it moves 3 over.

    [2, 3, 3]
    

    Since 1 is less than 2 it swaps moves 2 over.

    [2, 2, 3]
    

    Then it inserts 1 at the beginning.

    [1, 2, 3]
    

提交回复
热议问题