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
31 lines (27 loc) · 752 Bytes
/
binarySearch.py
File metadata and controls
31 lines (27 loc) · 752 Bytes
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
def binarySearch(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:
return mid
return -1
def userInput():
arr = []
n = int(input("Enter number of elements: "))
print("Enter the elements")
for i in range(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)
userInput()