Skip to content

Commit

Permalink
Merge pull request #147 from urmil22/optimize-binary-search
Browse files Browse the repository at this point in the history
optimize binary search
  • Loading branch information
Anjan50 authored Oct 28, 2023
2 parents a4c9cf7 + 92082e8 commit 307bf58
Showing 1 changed file with 11 additions and 26 deletions.
37 changes: 11 additions & 26 deletions Searching/binary_search.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,23 @@
#Binary_search using python
def binarySearch(arr, l, r, x):
def binary_search(arr, left, right, target):
while left <= right:
mid = (left + right) // 2

# Check base case
if r >= l:

mid = l + (r - l) // 2

# If element is present at the middle itself
if arr[mid] == x:
if arr[mid] == target:
return mid

# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid - 1, x)

# Else the element can only be present
# in right subarray
elif arr[mid] < target:
left = mid + 1
else:
return binarySearch(arr, mid + 1, r, x)

else:
# Element is not present in the array
return -1
right = mid - 1

return -1

# Driver Code
arr = [2, 3, 4, 10, 40]
x = 10
target = 10

# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
result = binary_search(arr, 0, len(arr) - 1, target)

if result != -1:
print("Element is present at index % d" % result)
print(f"Element is present at index {result}")
else:
print("Element is not present in array")

0 comments on commit 307bf58

Please sign in to comment.