[Programming Pearls] Column 2 – Binary Search

So, just a simple implementation of binary search…

def prog_2_A_binary_search(l, a, return_insertion_point = False):
    """
    >>> l = [1,20,34,45,76,87,90,100,103,298,500]
    >>> print(prog_2_A_binary_search(l, 298))
    9
    >>> print(prog_2_A_binary_search(l, 999))
    -1
    >>> print(prog_2_A_binary_search(l, 999, True))
    11
    >>> print(prog_2_A_binary_search(l, -22, True))
    0
    """
    lower = 0
    upper = len(l) - 1
    # on loop end condition:
    # [corner case] when lower == upper, we can still continue with
    # the logic as then mid will equal to lower / upper, so it won't break the logic
    while lower <= upper:
        # on calculation of mid:
        # 1. it will probably only happen to C: if we use (lower + upper) / 2,
        #    there will be risk where lower + upper exceeds the integer limitation
        # 2. as the remainder will be truncated, the mid is always either the middle one,
        #    or the one to the left of middle - which means if numbers cannot be found,
        #    upper can be within range [-1, len(l) - 1], lower can be within range [0, len(l)]
        mid = lower + ((upper - lower) >> 1)
        if a > l[mid]:
            lower = mid + 1
        elif a < l[mid]:
            upper = mid - 1
        else:
            return mid
    # on return value:
    # if we want to return a 'insertion point', meaning if
    # a is not in l, return i where i is either
    # 1. equivalent to len(l) if l[len - 1] < a
    # 2. l[i] > a
    # we can use return lower
    return lower if return_insertion_point else -1

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>