Reputation: 507
code is simple
def bubble_sort(l):
for i in xrange(0, len(l)-1) :
for n in xrange(0, len(l)) :
if l[i] > l[i+1] :
l[i], l[i+1] = l[i+1], l[i]
lst = [[1, 8, 2], [3, 2, 5], [2, 13, 3], [2, 5, 5], [2, 5, 6], [5, 11, 6], [5, 5, 6]]
print(lst)
bubble_sort(lst)
print(lst)
result:
[[1, 8, 2], [3, 2, 5], [2, 13, 3], [2, 5, 5], [2, 5, 6], [5, 11, 6], [5, 5, 6]]
[[1, 8, 2], [2, 13, 3], [2, 5, 5], [2, 5, 6], [3, 2, 5], [5, 5, 6], [5, 11, 6]]
the sort is not correct.
why?
Upvotes: 0
Views: 553
Reputation: 215009
The problem is that you're making only one iteration, while in bubble sort you should iterate over and over again until there are no swapped pairs anymore. Like this:
def bubble_sort(l):
ok = False
while not ok:
ok = True
for i in range(len(l) - 1):
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
ok = False
Upvotes: 2
Reputation: 51005
You must use n
as the indexing variable, not i
. As it is you're compare the same elements over and over len(l)
times. Try this:
def bubble_sort(l):
for i in xrange(0, len(l)) :
for n in xrange(0, len(l)-1) :
if l[n] > l[n+1] :
l[n], l[n+1] = l[n+1], l[n]
Upvotes: 1