# Binary Search

<figure><img src="https://3743232000-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHW2IQuh2PFpWJDvBz2FF%2Fuploads%2Fgit-blob-cffa9275310a69992fc9951a7ffdd18c191e8967%2FScreenshot%202023-01-20%20at%2020.00.11.png?alt=media" alt=""><figcaption></figcaption></figure>

### Binary Search has to be sorted before running

```jsx
function binarySearch(arr, target) {

  arr.sort((a, b) => a - b); // sorted Time complexity of insertion sort => n
  
  let s = -1;
  let e = arr.length;
  while (s + 1 < e) {
    const m = s + Math.floor((e - s) / 2);

    if (arr[m] >= target) {
      e = m;
    } else {
      s = m
    }
    
  }

  if (arr[e] !== target) 
    return -1;

  return e;
}

// Do not edit the line below.
exports.binarySearch = binarySearch;
```
