Skip to main content
Fixed to add syntax highlighting
Source Link
Sasha Chedygov
  • 131.6k
  • 27
  • 107
  • 117

That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:

 swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] > l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] > l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True 

Note that the whole idea is that the "bubble" moves along the array, swapping adjacent values until it moves through the list, with nothing swapped. There are a few optimizations that can be made (such as shrinking the size of the inner loop), but they are usually only worth bothering with when you are "homework oriented".

Edit: Fixed length() -> len()

That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:

 swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] > l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True 

Note that the whole idea is that the "bubble" moves along the array, swapping adjacent values until it moves through the list, with nothing swapped. There are a few optimizations that can be made (such as shrinking the size of the inner loop), but they are usually only worth bothering with when you are "homework oriented".

Edit: Fixed length() -> len()

That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:

swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] > l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True 

Note that the whole idea is that the "bubble" moves along the array, swapping adjacent values until it moves through the list, with nothing swapped. There are a few optimizations that can be made (such as shrinking the size of the inner loop), but they are usually only worth bothering with when you are "homework oriented".

Edit: Fixed length() -> len()

Source Link
jkerian
  • 17.2k
  • 3
  • 49
  • 59

That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:

 swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] > l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True 

Note that the whole idea is that the "bubble" moves along the array, swapping adjacent values until it moves through the list, with nothing swapped. There are a few optimizations that can be made (such as shrinking the size of the inner loop), but they are usually only worth bothering with when you are "homework oriented".

Edit: Fixed length() -> len()