Skip to content

Commit d8f62e6

Browse files
added comments
1 parent 655d1df commit d8f62e6

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

Binary_search.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,19 @@
33
def binarySearch(arr, l, r, x):
44
while l <= r:
55

6-
mid = l + (r - l) / 2;
6+
mid = l + (r - l) / 2; #extracting the middle element of the array
77

88
# Check if x is present at mid
99
if arr[mid] == x:
1010
return mid
1111

1212
# If x is greater, ignore left half
1313
elif arr[mid] < x:
14-
l = mid + 1
14+
l = mid + 1 #l is initialised to the rightmost element of the middle so that the search could be started from there the next time
1515

1616
# If x is smaller, ignore right half
1717
else:
18-
r = mid - 1
18+
r = mid - 1 #r is initialised to the leftmost element of the middle so that the search goes till there only the next time
1919

2020
# If we reach here, then the element was not present
2121
return -1
@@ -25,12 +25,14 @@ def binarySearch(arr, l, r, x):
2525
if __name__ == "__main__":
2626
# User input array
2727
print("Enter the array with comma separated in which element will be searched")
28-
arr = map(int, input().split(","))
28+
arr = map(int, input().split(",")) #the input array will of int type with each element seperated with a comma due to the split fucntion
29+
#map function returns a list of results after applying the given function to each item
2930
x = int(input("Enter the element you want to search in given array"))
3031

3132
# Function call
3233
result = binarySearch(arr, 0, len(arr) - 1, x)
33-
34+
35+
#printing the output
3436
if result != -1:
3537
print("Element is present at index {}".format(result))
3638
else:

0 commit comments

Comments
 (0)