# Programming Concepts: Binary search

Class | Search algorithm |
---|---|

Data structure | Array |

Worst case performance | O(log n) |

Best case performance | O(1) |

Average case performance | O(log n) |

Worst case space complexity | O(1) |

Binary search locates the position of an item in a **sorted** array.

A quick way to remember how this search works is to imagine searching for words beginning with 'S' in a dictionary. You know that the dictionary is in alphabetical order but you don't yet know if there are any words beginning with 'S' in it, nor do you know where the 'S' section begins and ends.

Description | Traced Alphabet |
---|---|

Open the Dictionary in the centre - you find the letter 'L' |
abcdefghijk |

how efficient is it? how many searches for x number of items? what is the equation? give an example. Why is it better than a linear search. Can you use it on ordered lists or unordered lists?

How to work out the maximum number of searches (n) on a x sized array:

2^n > size of list (x) where n = max searches

For example, if we had a 3 item array

2^2 = 4 > 3 therefore max searches = 2

```
min := 1;
max := N; {array size: var A : array [1..N] of integer}
repeat
mid := min + (max - min) div 2;
if x > A[mid] then
min := mid + 1;
else
max := mid - 1;
until (A[mid] = x) or (min > max);
```

*Note:* This code assumes 1-based array indexing. For languages that use 0-based indexing (most modern languages), *min* and *max* should be initialized to 0 and *N*-1.

*Note 2:* The code above does not return a result, nor indicates whether the element was found or not.

*Note 3:* The code above will not work correctly for empty arrays, because it attempts to access an element before checking to see if `min > max`

.

Exercise: Binary Search Given a 256 item sorted list, what is the maximum number of searches needed to find an item?
9 as:
2^n > size of list where n = max searches 2^9 = 512 > 256 Given a 1000 item sorted list, what is the maximum number of searches needed to find an item?
10 as:
2^n > size of list where n = max searches 2^10 = 1024 > 1000 |