1

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.

3
  • 1
    What is lst=lst supposed to do? Commented Dec 4, 2012 at 17:19
  • 1
    @NiclasNilsson Glorified pass statement? Commented Dec 4, 2012 at 17:33
  • yes.. i'm new to this, I still write codes in a very stupid way.... ;) Commented Dec 4, 2012 at 18:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't understand, why is that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.