# linear_search.py
"""Module to test out linear search code from CS1110 Lecture 21"""

def linear_search(b, h, k, v):
    """(see slides)"""
    i = h
    # inv: v not in b[h..i-1]
    while i <= k and b[i] != v:
        i = i + 1
    # post: b[i] = v and v not in b[h..i-1], or,
    #       i = k+1 and v not in b[h..k]
    n = i if i <= k else -1
    # post: b[n] = v and v not in b[h..i-1], or,
    #       n = -1 and v not in b[h..k]
    return n

def linear_search2(b, h, k, v):
    """(see slides)"""
    i = h
    # inv: v not in b[h..i-1]
    while i <= k:
        if b[i] == v:
            return i
        i = i + 1
    return -1
    # post: b[n] = v and v not in b[h..n-1], or,
    #       n = -1 and v not in b[h..k]

def linear_search3(b, h, k, v):
    """(see slides)"""
    # inv: v not in b[h..i-1]
    for i in range(h, k+1):
        if b[i] == v:
            return i
    return -1
    # post: b[ret.val.] = v and v not in b[h..i-1], or,
    #       ret.val. = -1 and v not in b[h..k]

if __name__ == '__main__':
    for f in [linear_search, linear_search2, linear_search3]:
        assert f([3,5,7,2,3], 1, 4, 7) == 2
        assert f([3,5,7,2,3], 1, 4, 9) == -1
        assert f([3,5,7,2,3], 1, 4, 3) == 4
        assert f([3,5,7,2,3], 1, 4, 5) == 1
        assert f([3,5,7,2,3], 1, 0, 3) == -1