Greetings! Today, we're exploring binary search, an efficient algorithm that pinpoints elements in a sorted list. It's analogous to locating a house number on a long street — rather than starting from one end, you begin in the middle and, based on whether the house number is higher or lower, you search the right or left half of the list.
We'll learn to:
- Understand binary search.
- Implement binary search using recursion and iteration in TypeScript.
- Analyze the time complexity of binary search.
Binary search is a classic example of the divide-and-conquer strategy. It starts by examining the middle element of a sorted list. If the middle element matches the target, you're done! If not, binary search eliminates half of the remaining elements based on whether the target is greater or smaller than the middle element. This process repeats until the target is found or the list is exhausted.
Let's implement binary search in TypeScript using recursion. Here's the code, accompanied by detailed comments:
This function calls itself recursively, gradually narrowing down the search area until it finds the target.
We can also visualize this search below:
Now, let's construct a binary search using a while
loop in TypeScript:
In this version, the function does not call itself. Instead, it uses a while
loop to accomplish the same goal.
Binary search reduces the input size by half at each step; thus, it takes steps to locate a target in an array of size n
. Consequently, the time complexity of binary search is .
Both recursive and iterative approaches share the same time complexity (). The choice between them typically depends on specific problems, constraints, and personal preference.
Great job! You've grasped the core of binary search, implemented it in TypeScript, and explored its time complexity. Up next, we have practice exercises to help you master binary search. Happy coding, and see you in the practice session!
