Binary Search
Computer Science: OCR GCSE, topic 2.1.10
Binary Search
Binary search is a type of algorithm known as a divide-and-conquer algorithm.

The concept
- If you try to find a certain page in a book, it's unlikely that you check every page on the way.
- You are more likely to split the book in two, then see if the page you need is before or after the split, and repeat.
- This is the concept behind the binary search.
- Data must be in a specific order. Example: lowest to highest, A->Z

In English
- Find a certain value within a range of values. Find the middle of the dataset.
- If the middle value is greater than the target then:
- Repeat on the first half of dataset. You can discard the second half of the dataset as you know all of these values are greater than the value you are trying to find.
- If the middle value is lesser than the target then:
- Repeat on the second half of dataset. This is the second half of the dataset after 50% was already removed when the first middle was found.
- If the middle value is the target:
- We found it!
- Stop repeating once the size of our dataset is zero.

In pseudocode

Example
- Task: Find the target value 23 in the sorted list:
- [5, 8, 12, 15, 19, 23, 27, 32]
- Step 1: Find the middle of the dataset
- List length = 8. Middle index = 8 / 2 = 4. Middle value = 19.
- Step 2: Compare with target
- 19 < 23. Target must be in the second half. Discard first half.
- New list: [23, 27, 32]
- Step 3: Find the middle of the new dataset
- New list length = 3. Middle index = 3 / 2 = 1. Middle value = 27
- Step 4: Compare with target
- 27 > 23. Target must be in the first half of the new list. Discard second half.
- New list: [23]
- Step 5: Find the middle again
- Middle value = 23
- Step 6: Compare with target
- 23 == 23
- Target found!

Pros and cons of binary search
- Pros:
- Faster than linear search on a large dataset.
- Cons:
- Dataset must be sorted before starting.
Test yourself on Binary Search
Binary search is an example of what type of algorithm?
What is the main advantage of binary search?