When you are dealing with an array that is in sorted order, there are new doors that open to find an element within the array. For example, finding the smallest item in a *sorted* array is just looking at the first element, and the same is true with finding the largest element as well! Not only that, there is another trick that makes finding any element in the array much faster than linear search, called Binary Search.

### Assumptions

- Knowledge of <a href="https://www.devmaking.com/learn/algorithms/big-o-notation/" target="_blank" style="color:inherit">Big-O notation</a>
- Familiarity with <a href="https://www.devmaking.com/learn/algorithms/master-theorem/" target="_blank" style="color:inherit">The Master Theorem</a>

# What is Binary Search?

Binary Search, known also as logarithmic search, is a *decrease and conquer* searching algorithm that finds elements in a sorted array by jumping to the midpoint of the array, comparing the midpoint to the item being searched for, and discarding the half of the array that is greater than or less than the item.
This continues until a single element is left and the item has been found.

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/Algs_BinarySearch_01.png" alt="binary-search diagram" style="max-width:95%;">

</div>

## Conceptualization

Let's say we have a sorted array `arr = { 1, 2, 4, 5, 8, 9, 12, 14, 17, 18, 20 }`

and are looking to find if the array contains `5`

. With linear search, we would have to check each element individually. Instead, we'll use binary search to find the element faster.

The length of `arr`

is 11. Dividing by 2 (and rounding down) will tell us that the midpoint of this starting array is `arr[5] == 9 `

.

`5 < 9`

, so we discard the top half of the array and look for the midpoint of the sub array `arr[0]`

to `arr[5]`

.

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/Algs_BinarySearch_02.png" alt="first binary search iteration" style="max-width:95%;">

</div>

The length of our sub-array is now 5. When divided by 2, and rounded down, the new midpoint is now `arr[2] == 4`

. This time `5 > 4`

, which means that we need to find the next midpoint between `arr[2]`

and `arr[5]`

.

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/Algs_BinarySearch_03.png" alt="second binary-search iteration" style="max-width:95%;">

</div>

The length of the current sub array is now 3. ` 3 / 2 = 1.5`

, which rounds down to 1. Because we are starting at `arr[2]`

, we add an offset of 1, making our new midpoint `arr[3]`

.

`arr[3] == 5`

: we have successfully found the value using binary search!

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/Algs_BinarySearch_04.png" alt="final binary-search iteration" style="max-width:95%;">

</div>

To model what just happened in code:

```
function binarySearch( int [] arr, int value ) {
// The left and right edges of the array
// these help define the sub array.
int left = 0;
int right = arr.length - 1;
// ( While the array is greater than 1 in size. )
while ( left <= right ){
// Find the midpoint of the sub array.
midpoint = floor( (left + right ) / 2 );
// If the value is greater than the midpoint..
if ( arr[midpoint] < value ) {
// .. Remove the left half of the array.
left = midpoint + 1;
}
// Or, if the value is less than the midpoint..
else if ( arr[midpoint] > value ) {
// .. Remove the right half of the array.
right = midpoint - 1;
}
// Otherwise, we've found the value!
else {
return midpoint;
}
}
// The value doesn't exist in the array!
return -1;
}
```

## Analyzing Binary Search

Binary search works by splitting an array into two pieces, only using one half for the next split. Utilizing only one of the two sub arrays is what makes this a decrease and conquer algorithm and not a divide and conquer algorithm, although both share in being able to utilize the recurrence relation solver.

Recalling <a href="https://www.devmaking.com/learn/algorithms/master-theorem/" target="_blank" style="color:inherit;">The Master Theorem</a>:

<div style="width:100%;text-align:center;font-style:italic;font-size:150%;">T(n) = aT( n/b ) + O(n<sup>d</sup>)</div> Taking this step by step:

- We jump to the midpoint of the remaining array each iteration;
`b = 2`

. - Then, we discard the half of the array that does not contain the value;
`a = 1`

. - Once the value is found, it is returned and no more work is done.
`O(1)`

,`d = 0`

.

This results in **T(n) = (1)T(n/2) + O(1)**.

Plugging this into the equation results in **0 = log<sub>2</sub>1**.

Using the corresponding formula yields:

<div style="width:100%;text-align:center;font-style:italic;font-size:150%;">n<sup>d</sup>log<sub>b</sub>n = n<sup>0</sup>log<sub>2</sub>n</sup></div> Which evaluates to a final result of:

<div style="width:100%;text-align:center;font-style:italic;font-size:150%;">O(log n)∎</div> <br>

Best | Worst | Average | Memory |
---|---|---|---|

O(1) | O(log n) | O(log n) | O(1) |

<br>

> Binary Search is an *optimal* searching algorithm with a worst case runtime of O(log n).

## When to Use Binary Search

- When you are working with a sorted array
- If the array is not sorted, it may be worth sorting the array if possible, especially if the array will need to be searched multiple times.

## Further Resources

<a href="https://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X/ref=as_li_ss_tl?_encoding=UTF8&pd_rd_i=032157351X&pd_rd_r=37c135e7-c5c4-4ed1-94ab-c2aaec60d692&pd_rd_w=PEuac&pd_rd_wg=xSJkC&pf_rd_p=1c11b7ff-9ffb-4ba6-8036-be1b0afa79bb&pf_rd_r=H3XK6W265MFMNYZ7PV3Z&psc=1&refRID=H3XK6W265MFMNYZ7PV3Z&linkCode=ll1&tag=devmaking-20&linkId=9f9600161b287607f80038c5fd85b020&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Algorithms (Sedgwick)</a> An excellent resource and reference for learning algorithms in computer science.

<a href="https://www.amazon.com/Algorithms-Sanjoy-Dasgupta-ebook-dp-B006Z0QR3I/dp/B006Z0QR3I/ref=as_li_ss_tl?_encoding=UTF8&me=&qid=1566246918&linkCode=ll1&tag=devmaking-20&linkId=26b190aacb9c02d1a0815d4066f9d80e&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Algorithms (Dasgupta)</a> Concise and clear overview on various types and designs of algorithms in a digestible format.

<a href="https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/ref=as_li_ss_tl?ie=UTF8&linkCode=ll1&tag=devmaking-20&linkId=1dd5be6066b180c12926dc03e2659215&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Introduction to Algorithms (CLRS)</a> An in depth and comprehensively detailed explanation of algorithms and how to design them.