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 i
isn't the smallest of lst[0:lst.index(i)]
, it still needs to be moved downwards. So, for example, if lst[0:lst.index(i)]
is [0, 1, 2, 4, 3]
, then even though the minimum is 0
, you still need to move 3
down a place for insertion sort to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.