Skip to content

Commit 8ca7963

Browse files
authored
Create Binarysearch_code
1 parent 52d62ac commit 8ca7963

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Binarysearch_code

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def binary_search(arr, target):
2+
low, high = 0, len(arr) - 1
3+
4+
while low <= high:
5+
mid = (low + high) // 2
6+
mid_value = arr[mid]
7+
8+
if mid_value == target:
9+
return mid # Target found, return its index
10+
elif mid_value < target:
11+
low = mid + 1 # Discard the left half
12+
else:
13+
high = mid - 1 # Discard the right half
14+
15+
return -1 # Target not found
16+
17+
# Example usage:
18+
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
19+
target_value = 6
20+
21+
result = binary_search(my_list, target_value)
22+
23+
if result != -1:
24+
print(f"Element {target_value} is present at index {result}.")
25+
else:
26+
print(f"Element {target_value} is not present in the list.")

0 commit comments

Comments
 (0)