Binary Search

    Search an exact number in array

    def binary_search(arr, number_researched):
        # (l)eft and (r)ight pointer
        l, r = 0, len(arr) - 1
        while l <= r:
            m = (l + r) // 2 # (m)id which is equivalent to math.floor((l+r) / 2)
            if arr[m] < number_researched:
                l = m + 1
            elif arr[m] > number_researched:
                r = m - 1
            else:
                return r
        return r
    

    Search closest number (floor)

    def binary_search(arr, number_researched):
        # (l)eft and (r)ight pointer
        l, r = 0, len(arr) - 1
        while l < r:
            m = (l + r) // 2
            if arr[m] < number_researched:
                l = m + 1
            else: # elif arr[m] >= number_researched:
                r = m
        return r