Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
Line 156: Line 156:
==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]
<pre>
def bubblesort(x):
def bubblesort(seq):
for i in range(len(x) - 2):
for j in range(i, len(x) - 1):
for i in xrange(len(seq) - 2):
if x[j] > x[j+1]:
for j in range(i, len(seq) - 1):
x[j], x[j+1] = x[j+1], x[j]
if seq[j] > seq[j+1]:
seq[j], seq[j+1] = seq[j+1], seq[j]
return x
x = [3, 78, 4, 23, 6, 8, 6]
bubblesort(x) # [3, 4, 6, 6, 8, 23, 78]


data = [3, 78, 4, 23, 6, 8, 6]
Python has a built in sort method:
bubblesort(data)

print data # [3, 4, 6, 6, 8, 23, 78]

</pre>
>>> foo = [3, 5, 2, 6, 1]
Python has a built in sort method, it's a quite modified Merge Sort called <b>Timsort</b>: http://py-stablesort.sourceforge.net/
>>> foo
<pre>
[3, 5, 2, 6, 1]
>>> foo.sort()
>>> foo = [3, 5, 2, 6, 1]
>>> foo
>>> foo
[1, 2, 3, 5, 6]
[3, 5, 2, 6, 1]
>>> foo.sort()

>>> foo
The built-in sort is not a bubble sort. TODO: I'm not sure what sort the python built-in is, but I'd imagine its fairly efficient.
[1, 2, 3, 5, 6]
</pre>


==[[Ruby]]==
==[[Ruby]]==