|
1 | 1 | # It returns location of x in given array arr
|
2 | 2 | # if present, else returns -1
|
3 | 3 | 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 |
5 | 7 |
|
6 |
| - mid = (l + r) // 2 # extracting the middle element from the array |
| 8 | + # Calculate the mid index |
| 9 | + mid = (l + r) // 2 |
7 | 10 |
|
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 |
11 | 14 |
|
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) |
16 | 18 |
|
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) |
23 | 22 |
|
24 | 23 |
|
25 | 24 | # Main Function
|
26 | 25 | if __name__ == "__main__":
|
27 | 26 | # 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: ")) |
34 | 31 |
|
35 | 32 | # Function call
|
36 | 33 | result = binary_search(arr, 0, len(arr) - 1, x)
|
|
0 commit comments