From d955a36e98c40f2b0a07a5d10d181cfa2c756a51 Mon Sep 17 00:00:00 2001 From: agarwalpranay02 Date: Mon, 27 Oct 2025 20:49:12 +0530 Subject: [PATCH] Create binary_search.py --- searching/binary_search.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 searching/binary_search.py diff --git a/searching/binary_search.py b/searching/binary_search.py new file mode 100644 index 000000000000..dadb51e0e20e --- /dev/null +++ b/searching/binary_search.py @@ -0,0 +1,28 @@ +""" +Binary Search (iterative) +Return index of target in sorted list, or -1 if not found. +""" + +from typing import List + +def binary_search(arr: List[int], target: int) -> int: + left, right = 0, len(arr) - 1 + while left <= right: + mid = left + (right - left) // 2 + if arr[mid] == target: + return mid + if arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return -1 + + +if __name__ == "__main__": + data = [2, 4, 6, 8, 10, 12, 14] + t = 10 + idx = binary_search(data, t) + if idx != -1: + print(f"Element found at index: {idx}") + else: + print("Element not found")