forked from souravjain540/Basic-Python-Programs
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.py
More file actions
Latest commit
43 lines (37 loc) · 1.09 KB
/
Copy pathbinarySearch.py
File metadata and controls
43 lines (37 loc) · 1.09 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
defbinarySearch(arr,target):
start=0
end=len(arr) -1
while ( start<=end ):
mid=start+ ( end-start ) //2
if (target<arr[mid]):
end=mid-1
elif (target>arr[mid]):
start=mid+1
else:
returnmid
return-1
defuserInput():
arr= []
n=int(input("Enter number of elements: "))
print("Enter the elements")
foriinrange(0,n):
element=int(input())
arr.append(element)
print(arr)
target=int(input("Enter the target element: "))
result=binarySearch(arr,target)
if(result==-1):
print("Element not found")
else:
print("The element was found at index ", result)
# Tests ('pip install pytest'; run with 'pytest binarySearch.py')
deftest_find_element_in_list():
arr= [11, 12, 22, 25, 34, 64, 90, 91]
result=binarySearch(arr, 25)
assertresult==3
deftest_elem_missing():
arr= [11, 12, 22, 25, 34, 64, 90, 91]
result=binarySearch(arr, 16)
assertresult==-1
if__name__=="__main__":
userInput()