Logo

Programming-Idioms

History of Idiom 124 > diff from v21 to v22

Edit summary for version 22 by Oldboy:
New Python implementation by user [Oldboy]

Version 21

2017-09-21, 18:07:58

Version 22

2017-10-28, 11:30:06

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
Imports
import bisect
Code
def binarySearch(a, x):
    i = bisect.bisect_left(a, x)
    return i if i != len(a) and a[i] == x else -1