From 0cb2d1618e8c21642b38840c0cd066fbf3e6f4a9 Mon Sep 17 00:00:00 2001 From: Amarelfaith <abubakarelfaith@gmail.com> Date: Thu, 12 Oct 2023 12:39:18 +0100 Subject: [PATCH] Added a binary_search.py algorithm --- binary_search.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 binary_search.py diff --git a/binary_search.py b/binary_search.py new file mode 100644 index 00000000..fea28736 --- /dev/null +++ b/binary_search.py @@ -0,0 +1,24 @@ +def binary_search(): + """ + Perform binary search on a sorted array to find the index of the target element. + If the target element is not found, return -1. + """ + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + target = int(input("Enter the target element: ")) + left = 0 + right = len(arr) - 1 + + while left <= right: + mid = (left + right) // 2 + + if arr[mid] == target: + return mid + elif arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return -1 + + +print(binary_search())