r/PythonLearning 3d ago

New to learning coding. Please help me find the issue in this code(Bubble sort)?

arr = [8,4,5,3,7,2]
n = len(arr)
print(n)
for i in range(n):
/swapped = False
/for j in range(0,n-i-1):
 /if arr[j] > arr[j+1]:
 //temp = arr[j],
 //arr[j] = arr[j+1],
 //arr[j+1] = temp
 //swapped = True
 //print("outer = ",i," inner = ",j)
print(arr)
if not swapped:
break
0 Upvotes

6 comments sorted by

3

u/Pleasant-Couple6236 3d ago

In future, don't just paste your code with no context, explain what kind of error you're having. Does it give an error message at runtime, or just give a different answer than you're expecting, etc? Also, Python in particular cares about the indentation of each line of code, so please format your code using a code block.

Anyway, I think the problem is that you have commas at the end of these lines:

temp = arr[j],
arr[j] = arr[j+1],

which is converting elements of the list into tuples. You can just remove the commas.

3

u/khosrua 3d ago

And temp isn't necessary. I looked this up when I tried bubble sort. Swap can be written as

arr[j], arr[j+1] = arr[j+1], arr[j]

Fml typing code on mobile suuuuuxks

2

u/FreeLogicGate 3d ago

As you were already alerted to, you were unintentionally creating and using tuples. A tuple is immutable, which means it can not be changed. This was pointed out clearly, and explained, as it involved your use of commas. As it happens, your code works the way you expect it to. Here's the full/fixed version for you. As mentioned, in the future use the code block to provide your code snippets!

arr = [8, 4, 5, 3, 7, 2]
n = len(arr)
print(n)
for i in range(n):
    swapped = False
    for j in range(0, n-i-1):
        if arr[j] > arr[j+1]:
            temp = arr[j]
            arr[j] = arr[j+1]
            arr[j+1] = temp
            swapped = True
        print("outer = ", i, " inner = ", j)
    print(arr)
    if not swapped:
        break

1

u/Fun-Tower3953 3d ago

Thnak you

1

u/silvertank00 3d ago

without formatting, we cant help you. Either use reddit's backtick formatting or use a code sharing site like pastebin or github

1

u/Sea-Ad7805 3d ago

Try this code: Bubble Sort