Sorting algorithms/Bogosort: Difference between revisions

added ruby
(added ruby)
Line 507:
Alternative definition for ''in_order'' (Python 2.5)
<python>def in_order(l):
return not l or all( l[i] <= l[i+1] for i in rangexrange(0,len(l)-1))</python>
 
An alternative implementation for Python 2.5 or later:
 
<python>import random
import random
def bogosort(lst):
random.shuffle(lst) # must shuffle it first or it's a bug if lst was pre-sorted! :)
while lst != sorted(lst):
random.shuffle(lst)
return lst</python>
 
</python>
=={{header|Ruby}}==
<ruby>def shuffle(l)
l.sort_by { rand }
end
 
def bogosort(l)
l = shuffle(l) until in_order(l)
l
end
 
def in_order(l)
(0..l.length-2).all? {|i| l[i] <= l[i+1] }
end</ruby>
 
An alternative implementation:
 
<ruby>def shuffle(l)
l.sort_by { rand }
end
 
def bogosort(l)
l = shuffle(l) until l == l.sort
l
end</ruby>
Anonymous user