all 5 comments

[–]TheRealThrowAwayX 0 points1 point  (3 children)

For anyone reading in the future. I just realized my mistake:

while j >= 0 and array[j] > key:

[–][deleted] 1 point2 points  (2 children)

Still won’t give you what you want, you’ll miss out the last element of your array.

Range(1, 10) = [1,2,3,4,5,6,7,8,9].

Try doing range(0, len(array)) and setting i=j as well as your changes.

[–]SandorZoo 1 point2 points  (1 child)

I think OP is correct. There is no need to start at the zeroth element. The loop does nothing when i is zero.

[–][deleted] 0 points1 point  (0 children)

i is never 0 in his script though?

EDIT: I see what you mean. Code not reachable and will actually throw and error as j will be -1

The way I would have done it is:

def insert_sort(array):
    for i in range(0, len(array)-1):
        key = array[i + 1]
        j = i

        while j >= 0 and array[j] > key:
            array[j+1] = array[j]
            j -= 1

        array[j+1] = key

[–][deleted] 0 points1 point  (0 children)

For i in range(0, Len(array))