Skip to content

Instantly share code, notes, and snippets.

@jcreinhold
Last active March 18, 2022 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcreinhold/61f88bfa6e8e679285faa16b3eee6baa to your computer and use it in GitHub Desktop.
Save jcreinhold/61f88bfa6e8e679285faa16b3eee6baa to your computer and use it in GitHub Desktop.
OCaml implementation of QuickSort
let swap arr i j =
let tmp = arr.(j) in
arr.(j) <- arr.(i);
arr.(i) <- tmp
let partition arr l h =
let pivot = arr.(h) in
let i = ref @@ (l - 1) in
for j = l to h - 1 do
if arr.(j) <= pivot then begin
incr i;
swap arr !i j
end
done;
incr i;
swap arr !i h;
!i
let partition_random arr l h =
let pivot_index = l + Random.int (h - l) in
swap arr pivot_index h;
partition arr l h
let quicksort xs =
let rec quicksort' arr l h =
if l < h then (
let pivot_index = partition_random arr l h in
quicksort' arr l (pivot_index - 1);
quicksort' arr (pivot_index + 1) h)
in
let arr = Array.of_list xs in
quicksort' arr 0 @@ (List.length xs - 1);
Array.to_list arr
let shuffle xs =
List.map (fun x -> (Random.bits (), x)) xs
|> List.sort compare |> List.map snd
let () =
Random.self_init ();
for _ = 1 to 20 do
List.init 10 (fun x -> x)
|> shuffle |> quicksort
|> List.iter (Printf.printf "%d ");
print_newline ()
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment