Skip to content

Commit b1b6f32

Browse files
authored
Added binary search in python
Added binary search in python using an iterative approach
1 parent 260cfec commit b1b6f32

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Searching Algorithms/binary_search.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# BINARY SEARCH
2+
3+
# It is a searching algorithm which is more efficient than linear search. It can find an element if present in O(log(n)) time complexity.
4+
# For this algorithm to work, the array should be in sorted order
5+
# it returns the position of the element in the array
6+
7+
8+
def binary_search (arr, item):
9+
"""The binary_Search function takes input the sorted list of elements and the item to be searched
10+
and returns the position of the item, if found in the list, else it returns -1 """
11+
beg, end = 0, len(arr)-1
12+
mid = (beg+end)//2
13+
14+
while beg<=end:
15+
mid = (beg+end)//2
16+
if arr[mid] == item :
17+
return mid
18+
elif arr[mid] > item:
19+
end = mid-1
20+
elif arr[mid] < item:
21+
beg = mid+1
22+
return -1 # return -1 if the element is not present in the array
23+
24+
25+
26+
## DRIVER CODE
27+
28+
test_arr = [1,2,3,4,5] # this should be a sorted array
29+
test_item = 2 # this is the item to be searched
30+
31+
ans = binary_search(test_arr, test_item)
32+
if ans != -1 :
33+
print(f"Element found at index position {ans}")
34+
else:
35+
print("Element is not present in array")

0 commit comments

Comments
 (0)