Logo

Programming-Idioms

History of Idiom 124 > diff from v17 to v18

Edit summary for version 18 by s:
[Ruby] added to comment

Version 17

2016-04-12, 20:15:00

Version 18

2016-06-17, 21:36:45

Idiom #124 Binary search for a value in sorted array

Write function binarySearch which returns the index of an element having value x in sorted array a, or -1 if no such element.

Idiom #124 Binary search for a value in sorted array

Write function binarySearch which returns the index of an element having value x in sorted array a, or -1 if no such element.

Extra Keywords
dichotomic dichotomy
Extra Keywords
dichotomic dichotomy
Code
def binary_search(ar, el)
  ar.bsearch_index{|x| x == el} || -1
end
Code
def binary_search(ar, el)
  ar.bsearch_index{|x| x == el} || -1
end
Comments bubble
Returning -1 is required, however index -1 refers to the last element of an array. More idiomatic is returning nil.
Comments bubble
Returning -1 is required, however index -1 refers to the last element of an array. More idiomatic is returning nil (which bsearch_index does).