Iterative Approach
In this iterative approach, instead of recursion, we use a while loop, and the loop runs until it hits the base condition, i.e. start becomes greater than end.
Example: This example shows the use of the above-explained approach.
javascript
// Iterative function to implement Binary Search let iterativeFunction = function (arr, x) { let start = 0, end = arr.length - 1; // Iterate while start not meets end while (start <= end) { // Find the mid index let mid = Math.floor((start + end) / 2); // If element is present at // mid, return True if (arr[mid] === x) return true ; // Else look in left or // right half accordingly else if (arr[mid] < x) start = mid + 1; else end = mid - 1; } return false ; } // Driver code let arr = [1, 3, 5, 7, 8, 9]; let x = 5; if (iterativeFunction(arr, x, 0, arr.length - 1)) { console.log( "Element found!" ); } else { console.log( "Element not found!" ); } x = 8; if (iterativeFunction(arr, x, 0, arr.length - 1)) { console.log( "Element found!" ); } else { console.log( "Element not found!" ); } |
Output
Element found! Element found!
Time Complexity: O(logN).
Auxiliary Space: O(1)
Binary Search In JavaScript
Binary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity
Examples:
Input : arr[] = {1, 3, 5, 7, 8, 9}, x = 5
Output : Element found!
Input : arr[] = {1, 3, 5, 7, 8, 9}, x = 6
Output : Element not found!
Note: Assuming the array is sorted.
These are the following ways to do Binary Search in JavaScript:
Table of Content
- Recursive Approach
- Iterative Approach
Contact Us