Skip to content

Commit ac7e04f

Browse files
committed
Added binary search program
1 parent 10242d1 commit ac7e04f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

B/Binary search/binary_search.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
This function implements the binary search algorithm to find the index of the target element in the given sorted array.
3+
4+
Parameters:
5+
arr (list): A sorted list of elements to be searched.
6+
target: The element to be found in the list.
7+
8+
Returns:
9+
int: Index of the target in the array if it exists, otherwise -1.
10+
"""
11+
def binary_search(arr, target):
12+
13+
left, right = 0, len(arr) - 1 # Initialize the left and right pointers
14+
15+
while left <= right:
16+
mid = (left + right) // 2 # Find the middle index
17+
18+
if arr[mid] == target: # Check if the middle element is the target
19+
return mid
20+
elif arr[mid] < target: # If the target is greater, ignore the left half
21+
left = mid + 1
22+
else: # If the target is smaller, ignore the right half
23+
right = mid - 1
24+
25+
return -1 # Return -1 if the target is not found
26+
27+
28+
# Example case
29+
arr = [2, 3, 4, 10, 40]
30+
target = 10
31+
result = binary_search(arr, target)
32+
33+
if result != -1:
34+
print(f"Element is present at index {result}.")
35+
else:
36+
print("Element is not present in array.")

0 commit comments

Comments
 (0)