Sorting algorithms/Bogosort: Difference between revisions

Content added Content deleted
(added ruby)
Line 507: Line 507:
Alternative definition for ''in_order'' (Python 2.5)
Alternative definition for ''in_order'' (Python 2.5)
<python>def in_order(l):
<python>def in_order(l):
return not l or all( l[i] < l[i+1] for i in range(0,len(l)-1))</python>
return all( l[i] <= l[i+1] for i in xrange(0,len(l)-1))</python>


An alternative implementation for Python 2.5 or later:
An alternative implementation for Python 2.5 or later:


<python>
<python>import random
import random
def bogosort(lst):
def bogosort(lst):
random.shuffle(lst) # must shuffle it first or it's a bug if lst was pre-sorted! :)
random.shuffle(lst) # must shuffle it first or it's a bug if lst was pre-sorted! :)
while lst != sorted(lst):
while lst != sorted(lst):
random.shuffle(lst)
random.shuffle(lst)
return 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>