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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With