Sorting algorithms/Bogosort: Difference between revisions

Content deleted Content added
Line 465: Line 465:
=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang Eiffel>
<lang Eiffel>

class
class
BOGO_SORT
BOGO_SORT

feature
feature

bogo_sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER]
bogo_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
do
-- Sorted array in ascending order.
from
until
do
from
is_sorted (ar) = TRUE
loop
until
Result:= shuffel(ar)
is_sorted (ar) = TRUE
loop
Result := shuffel (ar)
end
end
end

end
feature{NONE}
feature {NONE}

is_sorted (ar:ARRAY[INTEGER]): BOOLEAN
is_sorted (ar: ARRAY [INTEGER]): BOOLEAN
-- Is 'ar' sorted in ascending order?
require
require
not_void: ar /= Void
not_void: ar /= Void
Line 486: Line 493:
Result := True
Result := True
from
from
i := 1+ 1
i := 1 + 1
invariant
invariant
i >= 1 + 1 and i <= ar.count + 1
i >= 1 + 1 and i <= ar.count + 1
Line 499: Line 506:
end
end


shuffel(ar:ARRAY[INTEGER]): ARRAY[INTEGER]
shuffel (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
-- Array containing the same elements as 'ar' in a random shuffled order.
require
require
not_void: ar/= Void
not_void: ar /= Void
local
local
i,j:INTEGER
ith: INTEGER
i, j: INTEGER
ith: INTEGER
random: V_RANDOM
random: V_RANDOM
do
do
create random
create random
from
create Result.make_empty
i:=ar.count
Result.deep_copy (ar)
until
i<2
from
loop
i := ar.count
until
j:=random.bounded_item (1, i)
i < 2
ith:= ar[i]
loop
ar[i]:= ar[j]
j := random.bounded_item (1, i)
ar[j]:= ith
ith := Result [i]
random.forth
Result [i] := Result [j]
i:=i-1
Result [j] := ith
end
random.forth
Result:= ar
end
i := i - 1
end
end

end
end

</lang >
</lang >
TEST:
TEST:
<lang Eiffel>
<lang Eiffel>

class
class
APPLICATION
APPLICATION

inherit
ARGUMENTS


create
create
Line 539: Line 548:
make
make
do
do
test:= <<3,2,5,7,1>>
test := <<3, 2, 5, 7, 1>>
io.put_string ("Unsorted: ")
io.put_string ("Unsorted: ")
across
across test as t loop io.put_string (t.item.out + " ") end
test as t
loop
io.put_string (t.item.out + " ")
end
create sorter
create sorter
test:= sorter.bogo_sort (test)
test := sorter.bogo_sort (test)
io.put_string ("%NSorted: ")
io.put_string ("%NSorted: ")
across
across test as t loop io.put_string (t.item.out + " ") end
test as t
loop
io.put_string (t.item.out + " ")
end
end
end

test: ARRAY[INTEGER]
test: ARRAY [INTEGER]
sorter: BOGO_SORT

sorter: BOGO_SORT

end
end

</lang>
</lang>
{{out}}
{{out}}