Ns68
Ns68

Reputation: 77

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]

Upvotes: 2

Views: 181

Answers (3)

Hotone
Hotone

Reputation: 453

I believe you mixed up your indices i and j. It should read:

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]

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

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]

Upvotes: 3

Mateusz Puto
Mateusz Puto

Reputation: 78

You should use 'j' instead of 'i' in the body of the second loop. Otherwise it is pointless to have both loops. Only the outer loop is effectively executed.

Upvotes: 3

Related Questions