Bifalgorithm post
This is how to do a classic binary search. Given a sorted list of numbers and a target to search for, we can find that target in the array in log n time. If we have each of our indices from 0 to n minus 1, we'd get an index L at the beginning and an index R at the end. Then we'd iteratively calculate the middle, which is L plus R integer division by 2. Then we would check if our middle value is equal to the target. No, it's not. We haven't found it. But we know that our middle value is too big. It is bigger than the target. That means we would want to search in this range. So to search in this range, we would have to set r to be m minus 1 and then do this again. We would get our m now as this value and we'd see is this the target. No, it's not. This value is too small. So we set l to be m plus 1. And on our last iteration, we would see that the array at m is equal to our target. So we would return the index. Now in the alternate scenario, when that target's not even in the array, we actually get L and R are going to crisscross and usually return negative one. Follow me for more.
This is how to do a classic binary search. Given a sorted list of numbers and a target to search for, we can find that target in the array in log n time. If we…
Ideas in this flowchart
- Classic Binary Search
- Setup
- Sorted list and target
- Indices L and R
- Iterative Search Process
- Calculate middle index
- Middle value check
- Middle equals target
- Return index
- Middle too big
- Adjust R
- Middle too small
- Adjust L
- Target not in array
- L and R crisscross
- Return -1