Jump to content

Sorting algorithms/Bogosort: Difference between revisions

m
Line 465:
=={{header|Eiffel}}==
<lang Eiffel>
 
class
BOGO_SORT
 
feature
 
bogo_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
do
-- Sorted array in ascending order.
from
untildo
from
is_sorted (ar) = TRUE
loop until
Result:= is_sorted shuffel(ar) = TRUE
loop
Result := shuffel (ar)
end
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.
require
not_void: ar /= Void
local
i,j:INTEGER
i, ithj: INTEGER
test ith: ARRAY[INTEGER]
random: V_RANDOM
do
do
create random
from
create Result.make_empty
i:=ar.count
Result.deep_copy (ar)
until
i<2from
i := loopar.count
until
j:=random.bounded_item (1, i)
i < 2
ith:= ar[i]
loop
ar[i]:= ar[j]
j j:= random.bounded_item (1, i)
ar[j]:= ith
ith := Result:= ar[i]
random.forth
Result [i] := Result [j]
i:=i-1
Result ar[j] := ith
end
random.forth
Result:= ar
i := i - end1
end
end
 
end
 
</lang >
TEST:
<lang Eiffel>
 
class
APPLICATION
 
inherit
ARGUMENTS
 
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
across test as t loop io.put_string (t.item.out + " ") end
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
across 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
 
</lang>
{{out}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.