Lesson Introduction and Overview

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:

  1. Understand binary search.
  2. Implement binary search using recursion and iteration in TypeScript.
  3. Analyze the time complexity of binary search.
Unveiling 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.

Implementing Binary Search Using Recursion in TypeScript

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:

Implementing Binary Search Using Iteration in TypeScript

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.

Analyzing Complexity of Binary Search

Binary search reduces the input size by half at each step; thus, it takes log(n)\log(n) steps to locate a target in an array of size n. Consequently, the time complexity of binary search is O(logn)O(\log n).

Both recursive and iterative approaches share the same time complexity (O(logn)O(\log n)). The choice between them typically depends on specific problems, constraints, and personal preference.

Lesson Summary and Preview of Practice Exercises

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal