ocaml: phase 5.1 bs_rotated.ml baseline (rotated array search, encoded -66)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Binary search in a rotated sorted array. Standard sorted-half
test at each step:
if arr.(lo) <= arr.(mid) then
left half [lo, mid] is sorted -> check whether target is in it
else
right half [mid, hi] is sorted -> check whether target is in it
For [4; 5; 6; 7; 0; 1; 2]:
search 0 -> index 4
search 7 -> index 3
search 3 -> -1 (absent)
Encoded fingerprint: 4 + 3*10 + (-1)*100 = -66.
First baseline returning a negative top-level value; the runner
uses literal grep -qF so leading minus parses fine.
196 baseline programs total.
This commit is contained in:
25
lib/ocaml/baseline/bs_rotated.ml
Normal file
25
lib/ocaml/baseline/bs_rotated.ml
Normal file
@@ -0,0 +1,25 @@
|
||||
let bs_rotated arr target =
|
||||
let lo = ref 0 in
|
||||
let hi = ref (Array.length arr - 1) in
|
||||
let result = ref (-1) in
|
||||
while !lo <= !hi && !result = -1 do
|
||||
let mid = (!lo + !hi) / 2 in
|
||||
if arr.(mid) = target then result := mid
|
||||
else if arr.(!lo) <= arr.(mid) then begin
|
||||
if target >= arr.(!lo) && target < arr.(mid) then
|
||||
hi := mid - 1
|
||||
else
|
||||
lo := mid + 1
|
||||
end else begin
|
||||
if target > arr.(mid) && target <= arr.(!hi) then
|
||||
lo := mid + 1
|
||||
else
|
||||
hi := mid - 1
|
||||
end
|
||||
done;
|
||||
!result
|
||||
|
||||
;;
|
||||
|
||||
let a = [| 4; 5; 6; 7; 0; 1; 2 |] in
|
||||
bs_rotated a 0 + bs_rotated a 7 * 10 + bs_rotated a 3 * 100
|
||||
@@ -23,6 +23,7 @@
|
||||
"btree.ml": 39,
|
||||
"brainfuck.ml": 75,
|
||||
"bs_bounds.ml": 3211,
|
||||
"bs_rotated.ml": -66,
|
||||
"bsearch.ml": 7,
|
||||
"caesar.ml": 215,
|
||||
"calc.ml": 13,
|
||||
|
||||
Reference in New Issue
Block a user