Easy Tutorial
❮ Python Timstamp Str Python Socket ❯

Binary Search in Python

Python3 Examples

Binary search is a search algorithm that finds the position of a target value within a sorted array. It starts by comparing the target value to the middle element of the array. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater than the middle element, the search continues in the lower or upper half of the array, respectively, and the process is repeated. If the array becomes empty during this process, it means the target value is not present. This search algorithm halves the search range with each comparison.

Example: Recursive

# Returns the index of x in arr if present, else returns -1
def binarySearch(arr, l, r, x):

    # Base condition
    if r >= l:

        mid = int(l + (r - l)/2)

        # If the element is present at the middle itself
        if arr[mid] == x:
            return mid

        # If the element is smaller than mid, then it can only be present in the left subarray
        elif arr[mid] > x:
            return binarySearch(arr, l, mid-1, x)

        # Else the element can only be present in the right subarray
        else:
            return binarySearch(arr, mid+1, r, x)

    else:
        # Element is not present in the array
        return -1

# Test array
arr = [2, 3, 4, 10, 40]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
    print("Element is present at index %d" % result)
else:
    print("Element is not present in array")

Executing the above code outputs:

Element is present at index 3

Python3 Examples

❮ Python Timstamp Str Python Socket ❯