 Open in App
Not now

# Binary Search In JavaScript

• Difficulty Level : Easy
• Last Updated : 09 Feb, 2022

Binary Search is a searching technique which 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.
In this article, the implementation of Binary Search in Javascript is discussed using both iterative and recursive ways.
Given a sorted array of numbers. The task is to search for a given element in the array using Binary search.
Examples

```Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 5
Output : Element found!

Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 6

Note: Assuming the array is sorted.

Recursive Approach :

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

Below is the implementation of Binary Search (Recursive Approach) in JavaScript:

## javascript

 `                                     `

Output

```Element found!

Time Complexity: O(logN)
Auxiliary Space: O(1)
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.
Below is the implementation of Binary Search (Iterative Approach) in JavaScript:

## javascript

 `                                     `

Output

```Element found!