Sorting algorithms/Bogosort: Difference between revisions

(m)
Line 211:
 
<ocaml>
# let rec is_sorted comp (x::xs) = function
| e1 :: e2 :: r -> comp e1 e2 && is_sorted comp (e2 :: r)
let rec aux prev = function
| _ | [] -> true
| x::xs ->
if comp x prev then false
else aux x xs
in
aux x xs
;;
val is_sorted : ('a -> 'a -> bool) -> 'a list -> bool = <fun>
 
(* Fisher-Yates shuffle on lists; uses temp array *)
# Random.self_init();;
let shuffle l =
- : unit = ()
let ar = Array.of_list l in
 
# let shuffle for n = ListArray.sortlength (fun _ _ar -> Random.int1 3 -downto 1) ;;do
let k = Random.int (n+1) in
val shuffle : '_a list -> '_a list = <fun>
let temp = ar.(k) in (* swap ar.(k) and ar.(n) *)
 
ar.(k) <- ar.(n);
# let rec bogosort li =
if is_sorted ( < ar.(n) li then<- litemp
done;
else bogosort(shuffle li) ;;
Array.to_list ar
val bogosort : '_a list -> '_a list = <fun>
 
# let rec bogosort li =
if is_sorted ( < ) li then
inli
else
elsebogosort bogosort(shuffle li) ;;
</ocaml>
Example:
<pre>
# bogosort [7;5;12;1;4;2;23;18] ;;
- : int list = [1; 2; 4; 5; 7; 12; 18; 23]
</ocamlpre>
 
=={{header|Perl}}==
Anonymous user