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]
JavaScript
x
19
19
1
from array import *
2
mylist = array('i',[5,4,3,2,1,0])
3
4
def insertionsort(mylist):
5
if len(mylist)>1:
6
mylist = mylist[:len(mylist)-1]
7
insertionsort(mylist)
8
i = len(mylist)-1
9
key = mylist[i]
10
j = i-1
11
12
while j>=0 and key<mylist[j]:
13
mylist[j+1] = mylist[j]
14
j = j-1
15
mylist[j+1] = key
16
17
insertionsort(mylist)
18
print(mylist)
19
Advertisement
Answer
try this:
JavaScript
1
19
19
1
mylist = [5,4,3,2,1,0]
2
3
def insertionsort(mylist,n):
4
if n<=1:
5
return
6
insertionsort(mylist,n-1)
7
key = mylist[n-1]
8
j = n-2
9
10
while (j>=0 and key < mylist[j]):
11
mylist[j+1] = mylist[j]
12
j = j-1
13
14
mylist[j+1]=key
15
16
17
insertionsort(mylist, len(mylist))
18
print(mylist)
19
output:
JavaScript
1
2
1
[0, 1, 2, 3, 4, 5]
2