Reputation: 93
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)
Upvotes: 0
Views: 133
Reputation: 48
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
Upvotes: 0
Reputation: 1157
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!
Upvotes: 0
Reputation: 526583
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)
.
Upvotes: 1