Skip to content

Commit a538c43

Browse files
committed
Binary Search
1 parent ea49f86 commit a538c43

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

Searching-Algo/binarysearch.py

+32-9
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,42 @@
22
Binary Search
33
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
44
'''
5-
6-
def binarysearch(list,target):
7-
left=0
8-
right=len(list)-1
5+
# iterative approach
6+
def binarysearch(list, target):
7+
left = 0
8+
right = len(list)-1
99
while left <= right:
1010
mid = (left+right)//2
1111
if target == list[mid]:
1212
return mid
13-
elif target> list[mid]:
14-
left=mid+1
13+
elif target > list[mid]:
14+
left = mid+1
1515
else:
16-
right=mid-1
17-
16+
right = mid-1
17+
1818
return -1
1919

20-
print(binarysearch([2,3,4,5],5)) #3
20+
21+
print(binarysearch([2, 3, 4, 5], 5)) # 3
22+
23+
# recursive approach
24+
def binarysearch(list, left, right, target):
25+
if right >= left:
26+
mid = (left+right)//2
27+
28+
if target == list[mid]:
29+
return mid
30+
# If element is smaller than mid, then it can only
31+
# be present in left subarray
32+
elif list[mid] > target:
33+
return binarysearch(list, left, mid-1, target)
34+
# Else the element can only be present in right subarray
35+
else:
36+
return binarysearch(list, mid+1, right, target)
37+
else:
38+
return -1
39+
40+
41+
list = [2, 3, 4, 10, 11, 16, 90, 32, 7]
42+
target = 16
43+
print(binarysearch(list, 0, len(list)-1, target)) # 5

0 commit comments

Comments
 (0)