If you want to understand Binary Search in detail then refer to the binary search algorithm article.
Binary Search Algorithm
Let us assume that we have an unsorted array
n elements, and we want to find an element
n - 1.
lo + (hi - lo)/2.
X, we have found the element return the index
X,then discard the left half of elements and set
- Else if
X, then discard the right half of elements and set
Element is not found, so return
Python Program for Binary Search
def binary_search(arr, x, n): lo = 0 hi = n - 1 mid = 0 while lo <= hi: mid = (hi + lo) // 2 if arr[mid] < x: lo = mid + 1 elif arr[mid] > x: hi = mid - 1 else: return mid return -1 arr = [2, 3, 4, 1, 5] x = 4 n = len(arr) result = binary_search(arr, x, n) if result == -1: print("Element not found") else: print("Element is present at index", str(result))
Element is present at index 2