# search.py

""" Module for the alogorithms "linear search" and "binary_search"
"""

def linear_search(v, x):
    """
    Returns: index of first occurrence of x in v; -1 if not found.
    Parameter v: v is the list to search
    Parameter x: is the target value to search for
    """
    k= 0
    while k<len(v) and v[k]!=x:
        k= k+1

    if k<len(v):
        return k
    else:
        return -1

    # Concise alternative to the if-statement above:
    #    return k if k<len(v) else -1


def binary_search(v,x):
    """
    Returns: index of first occurrence of x in v; -1 if not found.
    Parameter v: v is the list to search
    Parameter x: is the target value to search for
    """
    i= 0          # index of left end of search window
    j= len(v)-1   # index of right end of search window

    # Keep halving search window until window no longer valid
    # i.e., keep halving search window as long as it is valid
    while i<=j:
        mid= (i+j)//2
        if v[mid] == x:
            return mid
        else:
            if v[mid] < x:
                i= mid + 1
            else:
                j= mid - 1
    return -1

    # Alternative while-loop setup
    """
    mid= (i+j)//2
    while i<=j and v[mid] != x:
        if v[mid] < x:
            i= mid + 1
        else:
            j= mid -1
        mid= (i+j)//2
    return -1 if i>j else mid
    """

