-2

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)
smci
  • 32,567
  • 20
  • 113
  • 146
  • As SrishtiAhuja said, on every iteration you're unwantedly shortening your list by dropping the last element: `mylist = mylist[:len(mylist)-1]`, so it will never get sorted. (Anyway, FYI in Python you don't need to keep referencing `len(mylist)`, you can use the slicing notation `ll[:-1]`) – smci Aug 22 '21 at 20:56

2 Answers2

1

This should work

from array import * 

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

def insertionsort(mylist, l): 
    if l>1: 
        insertionsort(mylist, l-1) 
    i=l-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, len(mylist)) 
print(mylist)
Srishti Ahuja
  • 181
  • 1
  • 7
  • Thanks for your help but could you help what is wrong with my program. Your help will be highly appreciated. – Surjit Singh Aug 22 '21 at 11:00
  • 1
    mylist=mylist[:len(mylist)-1] This statement is modifying your list. Try to print the status of your list after every recursive call in your code and you will understand where it is going wrong – Srishti Ahuja Aug 22 '21 at 11:08
0

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]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30