Definition
Binary search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. If the search ends with the remaining half being empty, the target is not in the array.
Constraints
- Data in an array must be sorted
Step-by-step explanation
Arguments:
- target value -
key - Sorted array -
array
Explanation:
- Divide search space into two halves, by selecting middle index as
mid - Compare
array[mid]withkey - If
array[mid]is equal tokeyreturn it's index - If
array[mid]isn't equal tokey, choose next half to be searched - If
array[mid]is bigger thankey, left side of anarrayshould be searched - If
array[mid]is smaller thankey, right side of anarrayshould be searched - Repeat until index of
keyis found or search space is empty
Returns:
Index of key or -1 if not found