Search code examples
pythonalgorithmrecursionsearchbinary-search

recursive binary search function that takes in and finds an array of keys (as opposed to a single key)


I need to make my binary search function search for multiple keys, not just one like I currently have. If the key is found return index of the key, else return -1.

example:

array = [ 1, 3, 5, 8, 10]
keys = [ 0, 2, 8, 5]

answer = [ -1, -1, 3, 2]

Help would be much appreciated!

def biSearch(A, low, high, key):

    mid = (high + low) // 2

    if low >= high: 
        return mid

    elif A[mid] >= key:        # we are in the left half of the array
        index = biSearch(A, low, mid, key)
        return index

    else:                   # we are in the right half of array
        index = biSearch(A, mid + 1 , high, key)
    return index


def search(A, key):
    low = 0
    high = len(A)
    index = biSearch(A, low, high, key)

    return index

Solution

  • Here is a way you might go about this:

    def _binary_search(arr, low, high, key):
        mid = (high + low) // 2
        if high - low <= 1:
            return low
        elif arr[mid] > key:
            return _binary_search(arr, low, mid, key)
        else:
            return _binary_search(arr, mid, high, key)
    
    def binary_search(arr, key):
        """
        Wraps the actual recursive search function, setting initial bounds and
        checking if the key was found or not.
        """
        index = _binary_search(arr, 0, len(arr), key)
        if arr[index] == key:
            return index
        return -1
    
    def vectorised_binary_search(arr, key_arr):
        return [binary_search(arr, key) for key in key_arr]
    
    print(vectorised_binary_search([1, 3, 5, 8, 10], [0, 2, 8, 5]))
    print(vectorised_binary_search(range(0, 10, 2), range(10)))
    

    which has output

    [-1, -1, 3, 2]
    [0, -1, 1, -1, 2, -1, 3, -1, 4, -1]
    

    I have taken the liberty of re-writing your binary search a little.