Skip to content

Commit 9e7bd10

Browse files
Merge pull request raviprakashdev#21 from Dhar15/kshitij
Added BinarySearch.py
2 parents 9fbe11a + 9ac2253 commit 9e7bd10

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

BinarySearch.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Iterative Binary Search Function
2+
# It returns index of x in given array arr if present,
3+
# else returns -1
4+
def binary_search(arr, x):
5+
low = 0
6+
high = len(arr) - 1
7+
mid = 0
8+
9+
while low <= high:
10+
11+
mid = (high + low) // 2
12+
13+
# Check if x is present at mid
14+
if arr[mid] < x:
15+
low = mid + 1
16+
17+
# If x is greater, ignore left half
18+
elif arr[mid] > x:
19+
high = mid - 1
20+
21+
# If x is smaller, ignore right half
22+
else:
23+
return mid
24+
25+
# If we reach here, then the element was not present
26+
return -1
27+
28+
29+
# Test array
30+
arr = [ 2, 3, 4, 10, 40 ]
31+
x = 10
32+
33+
# Function call
34+
result = binary_search(arr, x)
35+
36+
if result != -1:
37+
print("Element is present at index", str(result))
38+
else:
39+
print("Element is not present in array")

0 commit comments

Comments
 (0)