user6590825
user6590825

Reputation: 23

Python3 insertion sort iterating backwards not working

I'm a beginner in Python and am trying to implement insertion sort in the language. However, when I try my code on a list to sort I get the same list back. I figured out that the code isn't even going to the second loop. I am using Python 3. What is wrong with iterating backwards this way?

def ins_sort(us_in):
  tmp = None
  for key in range(1, len(us_in)-1):
    for i in range(key, 0, -1):
      if us_in[key] < us_in[i] and key != 0:
        tmp = us_in[key]
        us_in[key] = us_in[i]
        us_in[i] = tmp
  return us_in

print(ins_sort([5,2,4,6,1,3]))

Result:

[5,2,4,1,6,3]

Upvotes: 1

Views: 94

Answers (3)

badiya
badiya

Reputation: 2257

There are mainly 2 lines that you need to edit. 3rd line it should be len (us_in) not len(us_in)-1 And in the if statement it should be i >= 0 Instead of Key !=0 Also the second loop should start backward from key -1{ one less iteration}

Upvotes: 0

Tip: Put "prints" everywhere, these will help you following the state of your variables.

That said, try putting the tmp variable outside the "if" statement. And for running backwards, try this:

    for i in range(end):
        backwards = end - i
    #do something using "backwards" instead of "i"

Looks like you got your answer, anyway i won't delete this so you can keep the tip, as you're a begginer, print will be your best friend. trust me.

Upvotes: 0

Brian
Brian

Reputation: 1667

You have 2 issues in your code right now. Mouse over the yellow if you can't figure it out ;)

One is in this piece of code:

for key in range(1, len(us_in)-1):

You want to do for key in range(1, len(us_in)): so you reach every element of the list

And the other is in this block:

if us_in[key] < us_in[i] and key != 0:
    tmp = us_in[key]
    us_in[key] = us_in[i]
    us_in[i] = tmp

When you're iterating, key is staying the same as you're going through. You want it to be moving WITH i, not just stay stationary. You can replace every occurrence of i with i-1 and replace every key with i to fix this.

Upvotes: 1

Related Questions