Recursive Approach

  • BASE CONDITION: If the starting index is greater than the ending index return false.
  • Compute the middle index.
  • Compare the middle element with the number x. If equal return true.
  • If greater, call the same function with ending index = middle-1 and repeat step 1.
  • If smaller, call the same function with starting index = middle+1 and repeat step 1. 

Example: This example shows the use of the above-explained approach.

javascript




let recursiveFunction = function (arr, x, start, end) {
 
    // Base Condition
    if (start > end) return false;
 
    // Find the middle index
    let mid = Math.floor((start + end) / 2);
 
    // Compare mid with given key x
    if (arr[mid] === x) return true;
 
    // If element at mid is greater than x,
    // search in the left half of mid
    if (arr[mid] > x)
        return recursiveFunction(arr, x, start, mid - 1);
    else
 
        // If element at mid is smaller than x,
        // search in the right half of mid
        return recursiveFunction(arr, x, mid + 1, end);
}
 
// Driver code
let arr = [1, 3, 5, 7, 8, 9];
let x = 5;
 
if (recursiveFunction(arr, x, 0, arr.length - 1)) {
    console.log("Element found!");
}
else { console.log("Element not found!"); }
 
x = 6;
 
if (recursiveFunction(arr, x, 0, arr.length - 1)) {
    console.log("Element found!");
}
else { console.log("Element not found!"); }


Output

Element found!
Element not 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

Similar Reads

Recursive Approach:

BASE CONDITION: If the starting index is greater than the ending index return false. Compute the middle index. Compare the middle element with the number x. If equal return true. If greater, call the same function with ending index = middle-1 and repeat step 1. If smaller, call the same function with starting index = middle+1 and repeat step 1....

Iterative Approach:

...

Contact Us