What is Binary Search Algorithm?
Imagine you have a long list of items arranged in order, like numbers from 1 to 100. You want to find a specific number, let’s say 42, in the fastest way possible. Binary search is like a clever way of finding it without checking each number one by one.
Here’s how Binary Search Algorithm works:
- Start in the Middle:
- You don’t start from the beginning or the end; you start right in the middle of the list.
- In our example, the middle is 50 (halfway between 1 and 100).
- Is it the Number?
- You check if the number you’re looking for (42) is equal to the middle number (50).
- If yes, you found it!
- Narrow Down the Search:
- If 42 is smaller than 50, you now focus on the first half of the list (1 to 49).
- If 42 is larger than 50, you focus on the second half (51 to 100).
- Repeat the Process:
- Now, you repeat the process. Start in the middle of the narrowed-down list.
- If the middle number is 30, and you’re looking for 42, you know to focus on the right half (31 to 49).
- Keep Going Until You Find It:
- You keep splitting and narrowing down until you find the number you’re looking for.
Example of Binary Search Algorithm:
Let’s see how it works step by step:
- Start with the whole list: 1 to 100.
- Middle is 50. Is it 42? No. Since 42 is smaller, focus on the first half (1 to 49).
- Middle is 25. Is it 42? No. Since 42 is larger, focus on the second half (26 to 49).
- Middle is 37. Is it 42? No. Focus on the second half again (38 to 49).
- Middle is 43. Is it 42? Yes! You found it.
Binary search helps you find the right item much faster than checking each one individually. It’s like playing a guessing game, getting closer with each guess until you hit the bullseye.