I have a code in sml of binary search , the thing is when I search 20, output shows there is no element in an array even though array has 20. I can't figure out why is this happening.
open Array;
fun binsearch (A, x) =
let val n = length A;
val lo = ref 0 and hi = ref n;
val mid = ref ((!lo + !hi) div 2);
in
while ((!hi - !lo > 1) andalso (x <> sub (A, !mid))) do
(
if x < sub (A, !mid) then hi := !mid - 1
else lo := !mid + 1;
mid := (!lo + !hi) div 2
);
if x = sub (A, !mid) then SOME (!mid)
else NONE
end;
open Array;
val A = fromList [~24, ~24, ~12, ~12, 0, 0, 1, 20, 45, 123];
binsearch (A, 20);
binsearch (A, ~24);
binsearch (A, 123);
Code can't search number 20.