bubble sort in python:index out of range

106 views Asked by At

I am new to python and I was trying out bubble sort. Not able to find the error. Little help here.

def bubble(n, list):
    for i in range(0, n):
        for j in range(0, n - i - 1):
            if list[j] > list[j + 1]:
                list[j],list[j+1] = list[j + 1],list[j]

def main():
    n = input('size')
    n = int(n)
    list = []
    for i in range(0, n):
        no = input('no')
        list + [no]
    bubble(n, list)
    print(list)

main()

During execution, it's showing: line 4, in bubble if (list[j] > list[j + 1]): IndexError: list index out of range

But I couldn't find out how. The index always will be

1

There are 1 answers

0
CoderCharmander On BEST ANSWER

The first problem is that you don't convert the input('no') to int. It is not the cause of the current problem, but would cause problems later.

The second problem is that you use list as a variable name. list is a predefined Python class and you will overwrite it. Choose a different name.

The third problem is that you use list + [no]. That will not add no to list. It would just store the output temporarily and delete it automatically. There are 2 solutions: 1. Using += a += b is equal to a = a + b. This is also the case for many arithmetical operators. Just replace + with +=. 2. Using append append is faster. Use it like somelist.append(somevalue).