From 67cf7060b83cdc3efd5ad8b1f70fcf8085226212 Mon Sep 17 00:00:00 2001 From: G-Dinusha Date: Sat, 19 Oct 2024 10:30:36 +0530 Subject: [PATCH] Update binary_search.py --- Python-programming-1/binary_search.py | 51 ++++++++++++++++----------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/Python-programming-1/binary_search.py b/Python-programming-1/binary_search.py index 866e44e38..f944464a5 100644 --- a/Python-programming-1/binary_search.py +++ b/Python-programming-1/binary_search.py @@ -1,23 +1,32 @@ -def binarySearchAppr (arr, start, end, x): -# check condition -if end >= start: - mid = start + (end- start)//2 - # If element is present at the middle - if arr[mid] == x: - return mid - # If element is smaller than mid - elif arr[mid] > x: - return binarySearchAppr(arr, start, mid-1, x) - # Else the element greator than mid - else: - return binarySearchAppr(arr, mid+1, end, x) - else: - # Element is not found in the array - return -1 -arr = sorted(['t','u','t','o','r','i','a','l']) -x ='r' -result = binarySearchAppr(arr, 0, len(arr)-1, x) +def binarySearchAppr(arr, start, end, x): + # Check condition + if end >= start: + mid = start + (end - start) // 2 + + # If element is present at the middle + if arr[mid] == x: + return mid + + # If element is smaller than mid + elif arr[mid] > x: + return binarySearchAppr(arr, start, mid - 1, x) + + # Else the element is greater than mid + else: + return binarySearchAppr(arr, mid + 1, end, x) + + # Element is not found in the array + return -1 + +# Initialize and sort the array +arr = sorted(['t', 'u', 'o', 'r', 'i', 'a', 'l']) # Sort to ensure binary search works +x = 'r' + +# Perform binary search +result = binarySearchAppr(arr, 0, len(arr) - 1, x) + +# Check the result and print the appropriate message if result != -1: - print ("Element is present at index "+str(result)) + print("Element is present at index " + str(result)) else: -print ("Element is not present in array") + print("Element is not present in the array")