Skip to content

searches: add sentinel linear search algorithm #385

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 1 commit into from
Oct 2, 2018
Merged
Changes from all commits
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
62 changes: 62 additions & 0 deletions searches/sentinel_linear_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""
This is pure python implementation of sentinel linear search algorithm

For doctests run following command:
python -m doctest -v sentinel_linear_search.py
or
python3 -m doctest -v sentinel_linear_search.py

For manual testing run:
python sentinel_linear_search.py
"""

def sentinel_linear_search(sequence, target):
"""Pure implementation of sentinel linear search algorithm in Python

:param sequence: some sequence with comparable items
:param target: item value to search
:return: index of found item or None if item is not found

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

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

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

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

"""
sequence.append(target)

index = 0
while sequence[index] != target:
index += 1

sequence.pop()

if index == len(sequence):
return None

return index


if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3

user_input = raw_input('Enter numbers separated by comma:\n').strip()
sequence = [int(item) for item in user_input.split(',')]

target_input = raw_input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = sentinel_linear_search(sequence, target)
if result is not None:
print('{} found at positions: {}'.format(target, result))
else:
print('Not found')