0

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.

Aniket Saxena
  • 43
  • 1
  • 6

1 Answers1

0

The reason for this error is an off-by-one mistake in (!hi - !lo > 1) which should be either (!hi - !lo > 0) or (!hi - !lo >= 1).

ML is, however, intended to be a functional language. A more functional approach (i.e. without references and while loops) might look like this:

fun binsearch arr x =
let
  val l = Array.length arr
  fun subsearch arr x lo hi =
    if lo > hi then NONE
    else
      let
        val mid = (lo + hi) div 2
        val v = Array.sub (arr, mid)
      in
        if x < v then subsearch arr x lo (mid-1)
        else if x > v then subsearch arr x (mid+1) hi
        else SOME mid
      end
in
  subsearch arr x 0 (l-1)
end;
maxcampman
  • 156
  • 4