Logo

Programming-Idioms

History of Idiom 124 > diff from v22 to v23

Edit summary for version 23 by GobbleCock:
New Rust implementation by user [GobbleCock]

Version 22

2017-10-28, 11:30:06

Version 23

2018-06-12, 17:36:13

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
a.binary_search(&x).unwrap_or(-1);
Comments bubble
This only works if a is an array of signed integers.
Generally, a Result or Option would be more useful.
Doc URL
https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.binary_search