Jump to content

Binary search: Difference between revisions

From PASTE Wiki
Create binary search page
 
Add syntax highlighting to code example
Line 3: Line 3:
Example in Python:
Example in Python:


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

Revision as of 11:08, 4 January 2026

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