Logo

Programming-Idioms

History of Idiom 124 > diff from v31 to v32

Edit summary for version 32 by steenslag:
[Ruby] comply to variable name

Version 31

2020-10-08, 12:56:52

Version 32

2020-10-15, 17:33:58

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.

Variables
binarySearch,x,a
Variables
binarySearch,x,a
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(a, el)
  a.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 (which bsearch_index does).
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).