2

Here is my insertion sort, exactly the way it is in the book "introduction to algorithms":

def insertion_sort():
    A = [5,2,4,6,1,3]
    for j in range(1, len(A)):
        print 'j:'+str(j)
        key = A[j]
        print 'key:'+str(key)
        i=j-1
        print 'i:'+str(i)
        while i > 0 and A[i] > key:
            A[i+1] = A[i]
            i=i-1
            print 'new i: '+str(i)
        print 'swapping value: '+str(A[i]) + ' with value: '+str(A[i+1])
        print ' '
        A[i+1] = key
    print A

This prints:

[5, 1, 2, 3, 4, 6]

What am I doing wrong to have them out of order?

1 Answer 1

5

In Introduction to Algorithms, they always assume arrays start at index 1, so you are starting your range() at 1, but python lists are 0-based indexed. This means you are never comparing 5, which is at A[0]. Notice everything after 5 is sorted.

modifying your for loop to -

for j in range(0, len(A)):

and your while condition to

while i >= 0 and A[i] > key:

Should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.