Skip to content

Commit 009e607

Browse files
authored
Create Binary_search.py
Searching algorithm in logarithm time complexity.
1 parent 56a1f52 commit 009e607

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Binary_search.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# It returns location of x in given array arr
2+
# if present, else returns -1
3+
def binarySearch(arr, l, r, x):
4+
5+
while l <= r:
6+
7+
mid = l + (r - l)/2;
8+
9+
# Check if x is present at mid
10+
if arr[mid] == x:
11+
return mid
12+
13+
# If x is greater, ignore left half
14+
elif arr[mid] < x:
15+
l = mid + 1
16+
17+
# If x is smaller, ignore right half
18+
else:
19+
r = mid - 1
20+
21+
# If we reach here, then the element was not present
22+
return -1
23+
24+
# Main Function
25+
if __name__ == "__main__":
26+
# User input array
27+
print("Enter the array with comma separated in which element will be searched")
28+
arr = map(int,input().split(","))
29+
x = int(input("Enter the element you want to search in given array"))
30+
31+
# Function call
32+
result = binarySearch(arr, 0, len(arr)-1, x)
33+
34+
if result != -1:
35+
print("Element is present at index {}".format(result))
36+
else:
37+
print("Element is not present in array")

0 commit comments

Comments
 (0)