We'll learn to:
Understand Binary Search.
Implement Binary Search using recursion and iteration in JavaScript.
Analyse the time complexity of Binary Search.
Unveiling Binary Search
Binary Search follows a divide-and-conquer strategy. It starts in the middle of a sorted list. If the middle value is the desired one, great! If not, it uses the sorted nature of the list to eliminate half of it. The side to eliminate is selected based on whether the target is smaller or larger than the middle value.
Implementing Binary Search Using Recursion in JavaScript
Let's implement Binary Search in JavaScript using recursion. Here's the code, accompanied by detailed comments:
This function calls itself recursively, gradually shrinking the search area until it finds the target.
Implementing Binary Search Using Iteration in JavaScript
Here, we create a Binary Search using a while loop in JavaScript:
In this version, the function does not call itself. Instead, it uses a while loop to achieve the same goal.
Analysing Complexity of Binary Search
Binary Search reduces the input size by half on every step, hence it takes log(n) steps to find a target in an array of size n. Thus, the time complexity of Binary Search is O(log n). Both recursive and iterative approaches share the same time complexity — O(log n). Their choice usually comes down to specific problems, constraints, and personal preferences.
Comments
Post a Comment