(arr, l, r, x)
| 1 | # It returns location of x in given array arr |
| 2 | # if present, else returns -1 |
| 3 | def binary_search(arr, l, r, x): |
| 4 | # Base case: if left index is greater than right index, element is not present |
| 5 | if l > r: |
| 6 | return -1 |
| 7 | |
| 8 | # Calculate the mid index |
| 9 | mid = (l + r) // 2 |
| 10 | |
| 11 | # If element is present at the middle itself |
| 12 | if arr[mid] == x: |
| 13 | return mid |
| 14 | |
| 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) |
| 18 | |
| 19 | # Else the element can only be present in right subarray |
| 20 | else: |
| 21 | return binary_search(arr, mid + 1, r, x) |
| 22 | |
| 23 | |
| 24 | # Main Function |
no outgoing calls
no test coverage detected