Open In App

JavaScript Program for Binary Search using Recursion

Last Updated : 20 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will demonstrate the Binary Search in JavaScript using the Recursive approach.

Binary Search is a searching technique that works on the Divide and Conquer approach. It is faster than the linear search. It only works for the sorted arrays. It takes in O(log n) time for execution.

Approach

  • Create a function named recursiveBS that accepts 4 arguments i.e., array, target element, left index, and right index.
  • If the left index is greater than the right it means the element does not exist hence return -1.
  • Compute the mid index and check if the array at mid value is equal to the target then return the index.
  • Else if the target value is less than the mid element then call the function for the left half.
  • Else if the target value is greater than the mid element then call the function.
  • Call the recursiveBS for the given array and target element.
  • if the function returns -1 that means the element does not exist and print the output.
  • else output the index returned by the recursiveBS function using the console.log method.

Example: In this example, we will see the implementation of binary search using recursion.

Javascript




// Recursive function for binary search
function recursiveBS(arr, target, left, right) {
    // -1 for element not found
    if (left > right) return -1;
  
    // Get the mid index
    mid = Math.floor((left + right) / 2);
  
    // If target found return index
    if (arr[mid] === target) return mid;
    // If tagert is less than mid index value
    // search again in left half
    else if (arr[mid] > target) {
        return recursiveBS(arr, target, left, mid - 1);
    }
    // If target is greater than mid index value
    // search in right half
    else {
        return recursiveBS(arr, target, mid + 1, right);
    }
    return -1;
}
  
arr = [1, 2, 6, 7, 11, 13, 15, 18];
target = 7;
index = recursiveBS(arr, target, 0, arr.length - 1);
  
if (index == -1)
    console.log(
        target + " is not present in the given array"
    );
else 
    console.log(target + " is present at index: " + index);


Output

7 is present at index: 3

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads