algorithm - reverse numerical sort for list in python -


i'm trying create python implementations algorithms book i'm going through. though i'm sure python has these functions built in, thought exercise learn language bit.

the algorithm given create insertion sorting loop numerical array. able working fine. tried modify perform reverse sort (largest number lowest number). output there i'm not sure goes wrong.

first, sort increasing numbers:

sort_this = [31,41,59,26,41,58] print sort_this  j in range(1,len(sort_this)):     key = sort_this[j]     = j - 1     while >= 0 , sort_this[i] > key:         sort_this[i + 1] = sort_this[i]         -= 1     sort_this[i + 1] = key     print sort_this 

now, reverse sort not work:

sort_this = [5,2,4,6,1,3] print sort_this  j in range(len(sort_this)-2, 0, -1):     key = sort_this[j]     = j + 1     while < len(sort_this) , sort_this[i] > key:         sort_this[i - 1] = sort_this[i]         += 1         print sort_this     sort_this[i - 1] = key     print sort_this 

the output 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 sorted except first 2 numbers. have gone wrong?

range not include end value. when range(len(sort_this)-2, 0, -1), iteration goes len(sort_this)-2 1, never hit first element (at index 0). change range range(len(sort_this)-2, -1, -1)


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -