0

I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:

line 16, in <module> if listNums[x] < listNums[i]:

For this program:

    listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]

    x = 1
    i = 0
    Copy = 0

    for z in range (0, len(listNums)):
           if listNums[x] < listNums[i]:
                  Copy = listNums[i]
                  listNums[i] = listNums[x]
                  listNums[x] = Copy
           i = i + 1
           x = x + 1

    print(listNums)
2
  • 2
    What is the actual text of the rror you are getting? Commented Sep 5, 2016 at 23:48
  • the bisect module will do all the work for you... Commented Sep 6, 2016 at 0:08

3 Answers 3

1

Chances are it's a bounds error because x eventually increments up to len(listNums) which is 1 beyond the bounds of the zero-indexed array.

Try only iterating through range(0, len(listNums)-1).

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

Comments

0

I'd just like to point out that there is a better way to do it, namely

listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]

listNums.sort()
print listNums

which gives

[21, 32, 34, 38, 43, 54, 65, 65, 76, 98]
=> None

(compiled on repl.it)

Hope this helps!

Comments

0

This is not an insertion sort error In the last iteration i.e. len(listNums)th iteration, the value of x goes beyond the length of list that's why it gives IndexError: list index out of range

Comments

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.