Search code examples
pythonbubble-sort

Bubble sort not sorting properly in python


I'm making bubble sort in Python but have no idea why it doesn't sort properly.

N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
    for j in range(len(N)-i-1):
        if(N[i] > N[i+1]):
            N[i], N[i+1] = N[i+1], N[i]
print(N)

This is result of this code

[20, 40, 50, 10000, 50, 60, 90, 100, 5000, 22, 80000]

Solution

  • You should compare N[j] with N[j+1], because you need repeatedly swapping the adjacent elements if they are in wrong order.

    N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
    for i in range(len(N)-1):
        for j in range(len(N)-i-1):
            if(N[j] > N[j+1]):
                N[j], N[j+1] = N[j+1], N[j]
    print(N)
    

    Output

    [20, 22, 40, 50, 50, 60, 90, 100, 5000, 10000, 80000]