Skip to content

Update linear_search.py #2422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 14, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions searches/linear_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,39 @@ def linear_search(sequence, target):
return None


def rec_linear_search(sequence, low, high, target) -> int:
'''
Pure implementation of recursive linear search algorithm in Python

:param sequence: a collection with comparable items (as sorted items not required
in Linear Search)
:param low: Lower bound of the sequence
:param high: Higher bound of the sequence
:param target: The element to be found
:return: Index of the target or None if target not found

Examples:
>>> linear_search([0, 5, 7, 10, 15], 0)
0

>>> linear_search([0, 5, 7, 10, 15], 15)
4

>>> linear_search([0, 5, 7, 10, 15], 5)
1

>>> linear_search([0, 5, 7, 10, 15], 6)

'''
if high < low:
return None
if sequence[low] == target:
return low
if sequence[high] == target:
return high
return rec_linear_search(sequence, low + 1, high - 1, target)


if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item) for item in user_input.split(",")]
Expand Down