I wrote a code for insertion sort that now works great (yes, it’s homework). But, before that code I wrote a different one that doesn’t work and I just don’t know why. Please help me understand…
This is my older code:
def insertion_sort(lst):
if len(lst)==1:
lst=lst
else:
for i in lst[1:]:
if i==min(lst[0:lst.index(i)]):
lst.remove(i)
lst.insert(0, i)
return lst
I do not need a new insertion sort, I already wrote one. I just need the explanation for why this specific code didn’t work.
The problem is that sometimes, even though
iisn’t the smallest oflst[0:lst.index(i)], it still needs to be moved downwards. So, for example, iflst[0:lst.index(i)]is[0, 1, 2, 4, 3], then even though the minimum is0, you still need to move3down a place for insertion sort to work.