Jump to content

Binary search

From PASTE Wiki
Revision as of 11:08, 4 January 2026 by Admin (talk | contribs) (Add syntax highlighting to code example)

Binary search is a search algorithm to find a value in a sorted array. It works by starting at the middle of the array and checking if the target value is higher or lower than the middle value. If it is lower, the algorithm then treats the bottom half as the new array and repeats the process of checking the middle value until the target value is found. If the target is higher than the midpoint, the top half of the array is used.

Example in Python:

def binary_search(array, target):
    min = 0
    max = len(array)
    while min <= max:
        mid = (min + max) // 2
        if array[mid] < target:
            min = mid + 1
        elif array[mid] > target:
            max = mid - 1
        else:
            return mid
    # Not found
    return -1