Binary Search

What is Binary Search?

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, again taking the middle element to compare to the target value, and repeating this until the target value is found.

How to implement Binary Search?

Example

Let's implement binary search in Python.

def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1

Heart with ribbonBecome a SponsorHeart with ribbon

Become a sponsor and help us maintain and improve this project. Every contribution counts. Thank you!