Skip to content

Commit fcc7c74

Browse files
committed
Added searching.py
1 parent 8232f4d commit fcc7c74

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

searching.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import Union
2+
3+
from sorting import Sorting
4+
5+
6+
class Searching:
7+
@staticmethod
8+
def linear_search(list_to_search: list[object], element: object) -> Union[int, bool]:
9+
for i in range(len(list_to_search)):
10+
if list_to_search[i] == element:
11+
return i
12+
return False
13+
14+
@staticmethod
15+
def binary_search(list_to_search: list[float], element: float) -> Union[int, bool]:
16+
sorted_lst: list[float] = Sorting.merge_sort(list_to_search)
17+
start: int = 0
18+
end: int = len(sorted_lst) - 1
19+
while start <= end:
20+
mid: int = (end + start) // 2
21+
if sorted_lst[mid] < element:
22+
start = mid + 1
23+
elif sorted_lst[mid] > element:
24+
end = mid - 1
25+
else:
26+
return mid
27+
return False
28+
29+
30+
if __name__ == '__main__':
31+
test_list = [35, 10, 43, 82, 66, 51, 97]
32+
test_list_2 = [44, 11, 36, 52, 67, 83, 98]
33+
test_value_1 = 43
34+
test_value_2 = 44
35+
binary_result_1 = Searching.binary_search(test_list, test_value_1)
36+
print(binary_result_1)
37+
binary_result_2 = Searching.binary_search(test_list_2, test_value_2)
38+
print(binary_result_2)
39+
linear_result_1 = Searching.linear_search(test_list, test_value_1)
40+
print(linear_result_1)
41+
linear_result_2 = Searching.linear_search(test_list_2, test_value_2)
42+
print(linear_result_2)

0 commit comments

Comments
 (0)