Skip to content

Commit 18cb45c

Browse files
authored
modified Binary_search.py
result is not printing correctly
1 parent 9757b12 commit 18cb45c

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

Diff for: Binary_search.py

+18-21
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,33 @@
11
# It returns location of x in given array arr
22
# if present, else returns -1
33
def binary_search(arr, l, r, x):
4-
if l <= r:
4+
# Base case: if left index is greater than right index, element is not present
5+
if l > r:
6+
return -1
57

6-
mid = (l + r) // 2 # extracting the middle element from the array
8+
# Calculate the mid index
9+
mid = (l + r) // 2
710

8-
# If element is present at the middle itself
9-
if arr[mid] == x:
10-
return mid
11+
# If element is present at the middle itself
12+
if arr[mid] == x:
13+
return mid
1114

12-
# If element is smaller than mid, then it can only
13-
# be present in left subarray
14-
elif arr[mid] > x:
15-
return binary_search(arr, l, mid - 1, x)
15+
# If element is smaller than mid, then it can only be present in left subarray
16+
elif arr[mid] > x:
17+
return binary_search(arr, l, mid - 1, x)
1618

17-
# Else the element can only be present in right subarray
18-
else:
19-
return binary_search(arr, mid + 1, r, x)
20-
21-
# If we reach here, then the element was not present
22-
return -1
19+
# Else the element can only be present in right subarray
20+
else:
21+
return binary_search(arr, mid + 1, r, x)
2322

2423

2524
# Main Function
2625
if __name__ == "__main__":
2726
# User input array
28-
print("Enter the array with comma separated in which element will be searched")
29-
arr = [
30-
int(x) for x in input().split(",")
31-
] # the input array will of int type with each element seperated with a comma due to the split fucntion
32-
# map function returns a list of results after applying the given function to each item
33-
x = eval(input("Enter the element you want to search in given array"))
27+
arr = [int(x) for x in input("Enter the array with elements separated by commas: ").split(",")]
28+
29+
# User input element to search for
30+
x = int(input("Enter the element you want to search for: "))
3431

3532
# Function call
3633
result = binary_search(arr, 0, len(arr) - 1, x)

0 commit comments

Comments
 (0)