Skip to content

Commit a136fb4

Browse files
author
codehouseindia
authored
Merge pull request codehouseindia#475 from ankit10126/patch-1
Create binary search.py
2 parents 880ec92 + 446b792 commit a136fb4

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

binary search.py

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

0 commit comments

Comments
 (0)