Skip to content

Commit 48a392b

Browse files
authored
Merge pull request #24 from proPrateekSahu/main
Create BinarySearch
2 parents 7ca8f73 + 4fcc45c commit 48a392b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

BinarySearch

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def binary_search(arr, x):
2+
low = 0
3+
high = len(arr) - 1
4+
mid = 0
5+
6+
while low <= high:
7+
8+
mid = (high + low) // 2
9+
10+
11+
if arr[mid] < x:
12+
low = mid + 1
13+
14+
15+
elif arr[mid] > x:
16+
high = mid - 1
17+
18+
19+
else:
20+
return mid
21+
22+
23+
return -1
24+
25+
26+
# Test array
27+
arr = [ 1, 10, 15, 20, 30 ]
28+
x = 20
29+
30+
# Function call
31+
result = binary_search(arr, x)
32+
33+
if result != -1:
34+
print("Element is present at index", str(result))
35+
else:
36+
print("Element is not present in array")

0 commit comments

Comments
 (0)