DEV Community

Cover image for Linear Search but recursive
Dipankar Shaw
Dipankar Shaw

Posted on • Originally published at dipankarshaw.web.app

Linear Search but recursive

linear search but recursive, after all why not make your life hell.

def linear_search(arr: list[int], target: int, index: int = 0) -> int:
    if index == len(arr):
        return -1
    if target == arr[index]:
        return index
    return linear_search(arr=arr, target=target, index=index + 1)


n: int = [37, 82, 15, 64, 9, 58, 91, 26, 73, 46]
target: int = 46

index: int = linear_search(arr=arr, target=target, index=0)

if index == -1:
    print("target element not found.")
else:
    print(f"target element found at index {index}")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)