4
Binary search is an algorithm that looks for an element in a sorted data-structure by constantly dividing the search space in half.
Rosetta Code
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
Wikipedia
In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomic divide-and-conquer search algorithm and executes in logarithmic time.
Smallest # of bytes wins
Clarifications
- Example of calling the function/lambda/macro should be included, but don't count those chars!
- Output should be
> -1
if found, and<=-1
otherwise import binary_search
(20 bytes) DOES NOT count!- Implementation should run in O(log n), as algorithm dictates
Also see the code-golf StackExchange FAQ.
Example
> binary_search([1,3,5,6,7,8,8,10], 5);
4
> binary_search([1,3,5,6,7,8,8,10], 543);
-1
4Does our implementation have to be exactly as binary search does it? Does is have to be logarithmic time? – xnor – 2015-11-13T06:27:26.160
3Can the list have repeats? Are the entries whole numbers? You should give an example that doesn't have all consecutive values. – xnor – 2015-11-13T07:01:35.870
@xnor: Thanks for your comments, clarified. – A T – 2015-11-13T08:45:45.630
5Regarding your comments on some of the answers: 1. That's not a FAQ; it's the code-golf tag wiki. Also, there are two ordered lists on that page, and both have a 5th item. 2. Have built-in-to-some-languages solutions excluded is a suggestion that you exclude built-ins when writing up your challenge. That's all it is: a suggestion, not a rule. Built-ins are not forbidden by default, and the second revision of your question doesn't include the word implementation. – Dennis – 2015-11-13T13:30:16.283
6 start="3">
Why should the search be iterative ? – Labo – 2015-11-13T15:26:39.193