-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearching_Algorithms.py
More file actions
44 lines (35 loc) · 1.17 KB
/
Searching_Algorithms.py
File metadata and controls
44 lines (35 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def linear_search(arr, target):
"""
Perform a linear search for the target in the array.
:param arr: List of elements to search through.
:param target: The element to search for.
:return: Index of the target if found, otherwise -1.
"""
for index, element in enumerate(arr):
if element == target:
return index
return -1
def binary_search(arr, target):
"""
Perform a binary search for the target in the sorted array.
:param arr: Sorted list of elements to search through.
:param target: The element to search for.
:return: Index of the target if found, otherwise -1.
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ == "__main__":
# Example usage of searching algorithms
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 6
print("Unsorted array:", arr)
print("Linear search result:", linear_search(arr, target))
print("Binary search result:", binary_search(arr, target))