 # Binary Search

Objective : Write an algorithm to find an element in an sorted array

Input: A sorted array, arrA[] and an key

Output : Return true if element is found, else false.

Approach: The idea is to compare the middle element of array with the key, if key equal to the middle element , that’s it you have find your element, return true. If key is greater than the middle element, chuck out the first half of the array, you wont find your key in the first half and do the recursive search on the right half of the array and vice versa.

```If(mid_element==key)
return true;
else if (mid>key)
do recursive search on the right half of the array.
else
do recursive search on the left half of the array.```

Time Complexity: O(logN) –since we are eliminating half of the array with every comparison.

Complete Code:

Output:

```The 99 present in array a ??? :true
The 76 present in array a ??? :false```

### 2 thoughts on “Binary Search”

1. if (mid>key)
do recursive search on the left half of the array.

else
do recursive search on the right half of the array.

2. // Generic way to binary search any object types
public int binarySearch(Object[] a, Object key) {
// if(Objects.isNull(a) || Objects.isNull(key)) throw new IllegalArgumentException(“Invalid arguments”);
int low = 0;
int high = a.length-1;
int mid ;

while (low >> 1;
Comparable midVal = (Comparable) a[mid];
int cmp = midVal.compareTo(key);
if(cmp 0) {
high = mid-1;
}
else {
return mid;
}
}
return – (low+1);
}