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
The first problem is that you don't convert the
input('no')toint. It is not the cause of the current problem, but would cause problems later.The second problem is that you use
listas a variable name.listis 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 addnotolist. It would just store the output temporarily and delete it automatically. There are 2 solutions: 1. Using+=a += bis equal toa = a + b. This is also the case for many arithmetical operators. Just replace+with+=. 2. Usingappendappendis faster. Use it likesomelist.append(somevalue).