Skip to main content
Refinement
Source Link

Non-recursive approach:

# Binary search in a non-empty sorted array
def bin_search(a, val):
    l = 0
    r = len(a)
    # Trying to find val in a[l:r]
    while r - l > 1:
        m = (l + r) // 2
        if a[m] > val:
            r = m
        else:
            l = m
    return a[l] == val

Non-recursive approach:

# Binary search in sorted array
def bin_search(a, val):
    l = 0
    r = len(a)
    # Trying to find val in a[l:r]
    while r - l > 1:
        m = (l + r) // 2
        if a[m] > val:
            r = m
        else:
            l = m
    return a[l] == val

Non-recursive approach:

# Binary search in a non-empty sorted array
def bin_search(a, val):
    l = 0
    r = len(a)
    # Trying to find val in a[l:r]
    while r - l > 1:
        m = (l + r) // 2
        if a[m] > val:
            r = m
        else:
            l = m
    return a[l] == val
Source Link

Non-recursive approach:

# Binary search in sorted array
def bin_search(a, val):
    l = 0
    r = len(a)
    # Trying to find val in a[l:r]
    while r - l > 1:
        m = (l + r) // 2
        if a[m] > val:
            r = m
        else:
            l = m
    return a[l] == val