Anonymous user
Sorting algorithms/Bogosort: Difference between revisions
m
→{{header|Eiffel}}
Line 465:
=={{header|Eiffel}}==
<lang Eiffel>
class
BOGO_SORT
feature
bogo_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
do▼
-- Sorted array in ascending order.
from▼
▲ from
loop
Result := shuffel (ar)
end
▲ end
feature {NONE}
is_sorted (ar: ARRAY [INTEGER]): BOOLEAN
-- Is 'ar' sorted in ascending order?
require
not_void: ar /= Void
Line 486 ⟶ 493:
Result := True
from
i := 1 + 1
invariant
i >= 1 + 1 and i <= ar.count + 1
Line 499 ⟶ 506:
end
shuffel (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
-- Array containing the same elements as 'ar' in a random shuffled order.
i,
create Result.make_empty
Result.deep_copy (ar)
until▼
i :=
j:=random.bounded_item (1, i)▼
i < 2
loop
ar[j]:= ith▼
random.forth▼
Result [i] := Result [j]
▲ Result:= ar
i := i -
end
end
end
</lang >
TEST:
<lang Eiffel>
class
APPLICATION
create
Line 539 ⟶ 548:
make
do
test := <<3, 2, 5, 7, 1>>
io.put_string ("Unsorted: ")
across
across test as t loop io.put_string (t.item.out + " ") end▼
test as t
loop
end
create sorter
test := sorter.bogo_sort (test)
io.put_string ("%NSorted: ")
across
across test as t loop io.put_string (t.item.out + " ") end▼
test as t
loop
end
end
▲ test: ARRAY[INTEGER]
test: ARRAY [INTEGER]
sorter: BOGO_SORT▼
end
</lang>
{{out}}
|