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]