Home > Mobile >  sorting algorithm getting an 'index out of range' error
sorting algorithm getting an 'index out of range' error

Time:04-18

A sorting algorithm in ascending order:

import random

num=[]
for x in range(10):
    #x=0
    ran=(random.randint(1,99))
    num.append(ran)
    #x =1

print(num)

y=0


while y<11:
    y =1
    if num[y]>num[y 1]:
        num[y],num[y 1]=num[y 1],num[y]
        
    else:
        continue
print( num)
    

The error is:

 line 17, in <module>
    if num[y]>num[y 1]:
IndexError: list index out of range

CodePudding user response:

You are getting

IndexError: list index out of range

because num has 10 elements which means indices have to be between 0 and 9 (all inclusive). In your while, y ends up exceeding 9. You get this error when y is 9 as you attempt to make an access to an element with index y 1 (10).

By the way, even if you fix your IndexError your algorithm is not currently achieving what you want. One of the simplest ways is

import random

num = [random.randint(1, 99) for i in range(10)]

print(num)

for i in range(len(num)):
    for j in range(i   1, len(num)):
        if num[i] > num[j]:
            num[j], num[i] = num[i], num[j]

print(num)

Output

[62, 16, 16, 82, 69, 99, 83, 6, 41, 48]
[6, 16, 16, 41, 48, 62, 69, 82, 83, 99]

CodePudding user response:

The error indicates that for some value of y, y 1 is greater than the maximum index of num.

The maximum index of num is 9 because range(10) produces an array of length 10. However in your while loop y goes up to 10, which means y 1 goes up to 11. You can make the error go away by replacing y < 11 with y < 9.

However your algorithm doesn't work as is, because you only go through the array once. If you try it out with [8, 6, 3] you'll end up with [6, 3, 8]. Sorting by permutating adjacent elements is a valid method called Bubble sort but you have to go through the array multiple times, until there is no permutation left to do. That's why a bubble sort generally performs poorly.

  • Related