Questions tagged [binary-search]

Binary search is an efficient algorithm for finding an element in a sorted array. The basic idea is to cut the search space in half in each step. The complexity of the algorithm is O(log(n)).

A binary search (or "half-interval search") algorithm finds the position of a specified value (the input "key") within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.

A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

For pseudo-code and examples in multiple languages, check this Code Codex page.

2936 questions
31
votes
3 answers

Why in Java (high + low) / 2 is wrong but (high + low) >>> 1 is not?

I understand the >>> fixes the overflow: when adding two big positive longs you may end up with a negative number. Can someone explain how this bitwise shift magically fixes the overflow problem? And how it is different from >> ? My suspicion: I…
JohnPristine
  • 3,485
  • 5
  • 30
  • 49
31
votes
10 answers

Using Binary Search with sorted Array with duplicates

I've been tasked with creating a method that will print all the indices where value x is found in a sorted array. I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case. …
5StringRyan
  • 3,604
  • 5
  • 46
  • 69
30
votes
14 answers

Swift: Binary search for standard array?

I have a sorted array and want to do binary search on it. So I'm asking if something is already available in Swift library like sort etc.? Or is there a type independend version available? Of course I could write it by my own, but I like to avoid…
Peter71
  • 2,180
  • 4
  • 20
  • 33
30
votes
7 answers

TypeError: list indices must be integers, not float

I have a python 3.x program that is producing an error: def main(): names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci',…
Dahaka
  • 305
  • 1
  • 4
  • 6
30
votes
15 answers

Finding multiple entries with binary search

I use standard binary search to quickly return a single object in a sorted list (with respect to a sortable property). Now I need to modify the search so that ALL matching list entries are returned. How should I best do this?
Gruber
  • 4,478
  • 6
  • 47
  • 74
28
votes
16 answers

First occurrence in a binary search

I'm tinkering with some code and I realized something I never knew. A normal binary search will return a random index in a data set for a key that occurs more than once. How can I modify this code below to return the first occurrence? Is this…
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
28
votes
16 answers

Searching for an element in a circular sorted array

We want to search for a given element in a circular sorted array in complexity not greater than O(log n). Example: Search for 13 in {5,9,13,1,3}. My idea was to convert the circular array into a regular sorted array then do a binary search on the…
guirgis
  • 1,133
  • 2
  • 14
  • 17
27
votes
9 answers

Binary search with returned index in STL?

I need a binary search function. I couldn't find any function in the standard library that will return the index of the found item, and if it wasn't found, will return the bitwise complement of the index of the next element that is larger than the…
liran63
  • 1,300
  • 2
  • 15
  • 17
27
votes
2 answers

Why we write lo+(hi-lo)/2 in binary search?

I was reading about binary search...I know that the traditional way of finding mid value is like mid=(hi+lo)/2 But i also see that to avoid overflow mid value is calculated like that mid=lo+(hi-lo)/2 But why?? I couldn't find the actual…
user2291995
26
votes
3 answers

Get the largest key in a dictionary

I have a dictionary with keys that are ints. I would like to get the largest key. I don't keep track of keys so they might be consecutive (e.g. 1,2,3,4,5,6) but might skip (1,3,4,5) although I doubt that makes any difference. Do I just use a binary…
s5s
  • 11,159
  • 21
  • 74
  • 121
25
votes
5 answers

Implement binary search in objects

Is there any way to implement binary search in a ArrayList with objects? In this example the ArrayList will be sorted with the field 'id'. class User{ public int id; public string name; } ArrayList users = new…
Baversjo
  • 3,656
  • 3
  • 34
  • 47
25
votes
5 answers

Can LINQ use binary search when the collection is ordered?

Can I somehow "instruct" LINQ to use binary search when the collection that I'm trying to search is ordered. I'm using an ObservableCollection, populated with ordered data, and I'm trying to use Enumerable.First(). In my predicate, I'm…
luvieere
  • 37,065
  • 18
  • 127
  • 179
24
votes
5 answers

Insertion Sort with binary search

When implementing Insertion Sort, a binary search could be used to locate the position within the first i - 1 elements of the array into which element i should be inserted. How would this affect the number of comparisons required? How would using…
Derrek Whistle
  • 701
  • 2
  • 7
  • 16
23
votes
3 answers

Is golden section search better than binary search?

Recently I've heard an opinion that binary search may be improved by taking by splitting the range by phi (golden ration) instead of by 2. This was a big surprise to me, because I've never heard about such optimization. Is this true? Would this have…
Fixpoint
  • 9,619
  • 17
  • 59
  • 78
22
votes
4 answers

C# lambda expressions and IComparer

I am using lambda expressions to sort and search an array in C#. I don't want to implement the IComparer interface in my class, because I need to sort and search on multiple member fields. class Widget { public int foo; public void Bar() …
Justin Morgan
  • 2,427
  • 2
  • 16
  • 19