# Binary Search In JavaScript

Binary Search is searching technique which works on Divide and Conquer approach. It used to search any element in a sorted array.

As compared to linear, binary search is much faster with Time Complexity of O(logN) whereas linear search algorithm works in O(N) time complexity.

In this article, implement of Binary Search in Javascript using both iterative and recursive ways are discussed.

Given a sorted array of numbers. The task is to search 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.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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:

 `                                       `

Output:

```Element found!
```

Time Complexity: O(logN).

Iterative Approach : In this iterative approach instead of recursion, we will use a while loop and the loop will run until it hits the base condition i.e start becomes greater than end.

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

 `                                       `

Output:

```Element found!
```

Time Complexity: O(logN).

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : nidhi_biet