Skip to content
Advertisement

Insertion Sort Recursion not picking up last element [5,4,3,2,1,0] After sortin [1,2,3,4,5,0] Where last element not sorted

I have been stuck in the middle of the problem I am writing Recursive insertion sort on my own. The program works well but didn’t pick the last element to sort [5,4,3,2,1,0]. After the execution: [1,2,3,4,5,0]

from array import *
mylist = array('i',[5,4,3,2,1,0])

def insertionsort(mylist):
    if len(mylist)>1:
        mylist = mylist[:len(mylist)-1]
        insertionsort(mylist)
        i = len(mylist)-1
        key = mylist[i]
        j = i-1
        
        while j>=0 and key<mylist[j]:
            mylist[j+1] = mylist[j]
            j = j-1
        mylist[j+1] = key

insertionsort(mylist)
print(mylist)

Advertisement

Answer

try this:

mylist = [5,4,3,2,1,0]

def insertionsort(mylist,n):
    if n<=1:
        return
    insertionsort(mylist,n-1)
    key = mylist[n-1]
    j = n-2
     
    while (j>=0 and key < mylist[j]):
        mylist[j+1] = mylist[j]
        j = j-1
 
    mylist[j+1]=key


insertionsort(mylist, len(mylist))
print(mylist)

output:

[0, 1, 2, 3, 4, 5]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement