4

I'm trying to create python implementations from an algorithms book I'm going through. Though I'm sure that python probably has these functions built in, I thought it would be a good exercise to learn the language a bit.

The algorithm given was to create an insertion sorting loop for a numerical array. This I was able to get working just fine. I then tried to modify it to perform a reverse sort (largest number to lowest number). The output is almost there but I'm not sure where it goes wrong.

First, the sort for increasing numbers:

sort_this = [31,41,59,26,41,58]
print sort_this

for j in range(1,len(sort_this)):
    key = sort_this[j]
    i = j - 1
    while i >= 0 and sort_this[i] > key:
        sort_this[i + 1] = sort_this[i]
        i -= 1
    sort_this[i + 1] = key
    print sort_this

Now, the reverse sort which does not work:

sort_this = [5,2,4,6,1,3]
print sort_this

for j in range(len(sort_this)-2, 0, -1):
    key = sort_this[j]
    i = j + 1
    while i < len(sort_this) and sort_this[i] > key:
        sort_this[i - 1] = sort_this[i]
        i += 1
        print sort_this
    sort_this[i - 1] = key
    print sort_this

The output for the above is:

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

The final array is almost sorted except for the first 2 numbers. Where have I gone wrong?

1
  • 1
    Why not just use sort_this[i] < key? No need to loop in the other direction here. Commented May 19, 2013 at 20:08

1 Answer 1

8

range does not include the end value. When you do range(len(sort_this)-2, 0, -1), your iteration goes from len(sort_this)-2 to 1, so you never hit the first element (at index 0). Change your range to range(len(sort_this)-2, -1, -1)

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.