|
1 | 1 | """ |
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 |
11 | 5 | """ |
12 | 6 |
|
13 | 7 |
|
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: |
33 | 9 | """ |
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 |
35 | 22 |
|
36 | | - index = 0 |
37 | | - while sequence[index] != target: |
38 | | - index += 1 |
| 23 | + last = arr[n - 1] |
| 24 | + arr[n - 1] = target |
| 25 | + i = 0 |
39 | 26 |
|
40 | | - sequence.pop() |
| 27 | + while arr[i] != target: |
| 28 | + i += 1 |
41 | 29 |
|
42 | | - if index == len(sequence): |
43 | | - return None |
| 30 | + arr[n - 1] = last |
44 | 31 |
|
45 | | - return index |
| 32 | + if i < n - 1 or arr[n - 1] == target: |
| 33 | + return i |
| 34 | + return -1 |
46 | 35 |
|
47 | 36 |
|
48 | 37 | 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