Advertisement
thebullno1

bsearch

Oct 2nd, 2012
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 0.46 KB | None | 0 0
  1. bsearch(Key, Array) -> bsearch(Key, 0, array:size(Array) - 1, Array). %Default range
  2.  
  3. bsearch(Key, From, To, Array) when From <= To -> %when there's hope
  4.     Mid = (To + From) div 2,
  5.     MidValue = array:get(Mid, Array),
  6.     if
  7.         Key < MidValue -> bsearch(Key, From, Mid - 1, Array);
  8.         Key = MidValue -> Mid;
  9.         Key > MidValue -> bsearch(Key, Mid + 1, To, Array);
  10.     end;
  11.  
  12. bsearch(_Key, _From, _To, _Array) -> not_found; %When it's hopeless, return -1 is too mainstream
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement