Skip to content

Commit 2d20411

Browse files
Merge pull request #37 from naveentata/master
Python Code for BinarySearch
2 parents 700de33 + f0cd694 commit 2d20411

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Code/BinarySearch.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def BinarySearch(array, low, high, find):
2+
3+
while low <= high:
4+
5+
mid = low + (high - low)//2;
6+
7+
8+
if array[mid] == find:
9+
return mid
10+
11+
12+
elif array[mid] < find:
13+
low = mid + 1
14+
15+
16+
else:
17+
high = mid - 1
18+
19+
# If the element is not present it returns -1
20+
return -1
21+
22+
23+
# Sample array
24+
arr = [ 2, 3, 4, 10, 40 ]
25+
find = 2
26+
27+
28+
found = BinarySearch(arr, 0, len(arr)-1, find)
29+
30+
if found != -1:
31+
print ("Given element %d is found at index %d" %(find, found))
32+
else:
33+
print ("Given element is not present in the given array")
34+

0 commit comments

Comments
 (0)