Reverse numerical sorting for a list in python

I am trying to create python implementations from a book of algorithms that I am looking at. Although I'm sure python may have these functions built in, I thought it would be a good exercise to learn a little language.

The above algorithm consisted of creating an insertion sorting cycle for a numerical array. This I was able to work normally. Then I tried to change it to do reverse sorting (highest number to lowest number). The output is almost there, but I'm not sure where it goes wrong.

Firstly, sorting to increase the number:

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 reverse sorting doesn't 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 

Output for above:

 [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 two numbers. Where am I wrong?

+4
source share
1 answer

range does not include the final 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)

+8
source

Source: https://habr.com/ru/post/1481657/


All Articles