Reputation: 77
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
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
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
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