-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #147 from urmil22/optimize-binary-search
optimize binary search
- Loading branch information
Showing
1 changed file
with
11 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |