Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse numerical sort for list in python

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?

like image 834
marauder Avatar asked Feb 17 '23 12:02

marauder


1 Answers

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)

like image 128
BrenBarn Avatar answered Feb 19 '23 02:02

BrenBarn