Skip to content

Commit 0770595

Browse files
feat: Add sentinel linear search algorithm
1 parent 791deb4 commit 0770595

1 file changed

Lines changed: 28 additions & 46 deletions

File tree

searches/sentinel_linear_search.py

Lines changed: 28 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,40 @@
11
"""
2-
This is pure Python implementation of sentinel linear search algorithm
3-
4-
For doctests run following command:
5-
python -m doctest -v sentinel_linear_search.py
6-
or
7-
python3 -m doctest -v sentinel_linear_search.py
8-
9-
For manual testing run:
10-
python sentinel_linear_search.py
2+
Sentinel Linear Search Algorithm
3+
A variation of linear search that reduces comparisons.
4+
Reference: https://en.wikipedia.org/wiki/Linear_search#With_a_sentinel
115
"""
126

137

14-
def sentinel_linear_search(sequence, target):
15-
"""Pure implementation of sentinel linear search algorithm in Python
16-
17-
:param sequence: some sequence with comparable items
18-
:param target: item value to search
19-
:return: index of found item or None if item is not found
20-
21-
Examples:
22-
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
23-
0
24-
25-
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
26-
4
27-
28-
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
29-
1
30-
31-
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
32-
8+
def sentinel_linear_search(arr: list[int], target: int) -> int:
339
"""
34-
sequence.append(target)
10+
Search for target using sentinel method, return index or -1 if not found.
11+
12+
>>> sentinel_linear_search([1, 2, 3, 4, 5], 3)
13+
2
14+
>>> sentinel_linear_search([1, 2, 3, 4, 5], 6)
15+
-1
16+
>>> sentinel_linear_search([], 1)
17+
-1
18+
"""
19+
n = len(arr)
20+
if n == 0:
21+
return -1
3522

36-
index = 0
37-
while sequence[index] != target:
38-
index += 1
23+
last = arr[n - 1]
24+
arr[n - 1] = target
25+
i = 0
3926

40-
sequence.pop()
27+
while arr[i] != target:
28+
i += 1
4129

42-
if index == len(sequence):
43-
return None
30+
arr[n - 1] = last
4431

45-
return index
32+
if i < n - 1 or arr[n - 1] == target:
33+
return i
34+
return -1
4635

4736

4837
if __name__ == "__main__":
49-
user_input = input("Enter numbers separated by comma:\n").strip()
50-
sequence = [int(item) for item in user_input.split(",")]
51-
52-
target_input = input("Enter a single number to be found in the list:\n")
53-
target = int(target_input)
54-
result = sentinel_linear_search(sequence, target)
55-
if result is not None:
56-
print(f"{target} found at positions: {result}")
57-
else:
58-
print("Not found")
38+
import doctest
39+
40+
doctest.testmod()

0 commit comments

Comments
 (0)