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
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 addno
tolist
. It would just store the output temporarily and delete it automatically. There are 2 solutions: 1. Using+=
a += b
is equal toa = a + b
. This is also the case for many arithmetical operators. Just replace+
with+=
. 2. Usingappend
append
is faster. Use it likesomelist.append(somevalue)
.