---
# System prepended metadata

title: '-Binary search (*for sorted array only)'
tags: [Easy]

---

# -Binary search (*for sorted array only)
###### tags: `Easy`

```cpp=
#include <vector>
using namespace std;

int binarySearch(vector<int> array, int target);
int binarySearchHelper(vector<int> array, int target, int right, int left);

int binarySearch(vector<int> array, int target) {
  // Sorted array only
  return binarySearchHelper(array, target, 0, array.size()-1);
}

int binarySearchHelper(vector<int> array, int target, int left, int right){
    while (left <= right){
        int middle = (right + left) / 2;
        if (target == array[middle]) 
            return middle;
        else if (target < array[middle])
            right = middle - 1;
        else
            left = middle + 1;
    }
    return -1;
}
```