From e0ce50fb1c1aee5fd2c7d3713d3f97f81c29e060 Mon Sep 17 00:00:00 2001 From: rajeshwariramya <103486631+rajeshwariramya@users.noreply.github.com> Date: Sat, 19 Oct 2024 10:26:19 +0530 Subject: [PATCH] Update Binary-Search.py --- Python/Binary-Search.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Python/Binary-Search.py b/Python/Binary-Search.py index 4c8d85f..67ec1b3 100644 --- a/Python/Binary-Search.py +++ b/Python/Binary-Search.py @@ -1,20 +1,25 @@ +# Define the array and target array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 7 + +# Initialize pointers left = 0 right = len(array) - 1 -found = False +found_index = -1 # To store the index if found +# Perform binary search while left <= right: mid = left + (right - left) // 2 if array[mid] == target: - found = True + found_index = mid break elif array[mid] < target: left = mid + 1 else: right = mid - 1 -if found: - print("Element found at index:", mid) +# Output the result +if found_index != -1: + print("Element found at index:", found_index) else: print("Element not found")