ocaml: phase 5.1 quickselect.ml baseline (median of 9 elements = 5)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Hoare quickselect with Lomuto partition: recursively narrows the
range to whichever side contains the kth index. Mutates the array
in place via .(i)<-v. The median (k=4) of [7;2;9;1;5;6;3;8;4] is 5.
let rec quickselect arr lo hi k =
if lo = hi then arr.(lo)
else begin
let pivot = arr.(hi) in
let i = ref lo in
for j = lo to hi - 1 do
if arr.(j) < pivot then begin
let t = arr.(!i) in
arr.(!i) <- arr.(j); arr.(j) <- t;
i := !i + 1
end
done;
...
end
Exercises array literal syntax + in-place mutation in the same
program, ensuring [|...|] yields a mutable backing.
138 baseline programs total.
This commit is contained in:
@@ -110,6 +110,7 @@
|
||||
"prime_factors.ml": 17,
|
||||
"pythagorean.ml": 16,
|
||||
"queens.ml": 2,
|
||||
"quickselect.ml": 5,
|
||||
"quicksort.ml": 44,
|
||||
"roman.ml": 44,
|
||||
"reverse_int.ml": 54329,
|
||||
|
||||
25
lib/ocaml/baseline/quickselect.ml
Normal file
25
lib/ocaml/baseline/quickselect.ml
Normal file
@@ -0,0 +1,25 @@
|
||||
let rec quickselect arr lo hi k =
|
||||
if lo = hi then arr.(lo)
|
||||
else begin
|
||||
let pivot = arr.(hi) in
|
||||
let i = ref lo in
|
||||
for j = lo to hi - 1 do
|
||||
if arr.(j) < pivot then begin
|
||||
let t = arr.(!i) in
|
||||
arr.(!i) <- arr.(j);
|
||||
arr.(j) <- t;
|
||||
i := !i + 1
|
||||
end
|
||||
done;
|
||||
let t = arr.(!i) in
|
||||
arr.(!i) <- arr.(hi);
|
||||
arr.(hi) <- t;
|
||||
if !i = k then arr.(!i)
|
||||
else if !i < k then quickselect arr (!i + 1) hi k
|
||||
else quickselect arr lo (!i - 1) k
|
||||
end
|
||||
|
||||
;;
|
||||
|
||||
let a = [|7; 2; 9; 1; 5; 6; 3; 8; 4|] in
|
||||
quickselect a 0 8 4
|
||||
Reference in New Issue
Block a user