How does Python insertion sort work?

前端 未结 21 1678
南方客
南方客 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:21

    The python range(start, end) function starts counting from start to end - 1. That is, end will never be part of the range() values. So if you have, for example, range(len(A)), and A is an array (in Python, a list) of 10 integers, len(A) will be 10, and range(len(A)) will return (0,1,2,3,4,5,6,7,8,9) so you can index every element in A.

    In your case, i never gets bigger than len(s) - 1.

    Following your code on paper can be useful, but you have to make sure that the programming language does exactly what you think it does, and sometimes the implementation isn't intuitive. A fast and simple way of tracing your program values is to use print statements. For example:

    def sort_numbers(s):
        for i in range(1, len(s)):
    
            # let's see what values i takes on
            print "i = ", i
    
            val = s[i]
            j = i - 1
            while (j >= 0) and (s[j] > val):
                s[j+1] = s[j]
                j = j - 1
            s[j+1] = val
    

提交回复
热议问题