Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update binary_search.py #2971

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 30 additions & 21 deletions Python-programming-1/binary_search.py
Original file line number Diff line number Diff line change
@@ -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")