File tree Expand file tree Collapse file tree 1 file changed +15
-15
lines changed
Expand file tree Collapse file tree 1 file changed +15
-15
lines changed Original file line number Diff line number Diff line change 11# It returns location of x in given array arr
22# if present, else returns -1
33def binarySearch (arr , l , r , x ):
4- while l <= r :
5-
6- mid = l + (r - l ) / 2 #extracting the middle element from the array
7- mid = int (mid ) #it has to be integer
8-
9- # Check if x is present at mid
4+ if l <= r :
5+
6+ mid = (l + r ) // 2 #extracting the middle element from the array
7+
8+ # If element is present at the middle itself
109 if arr [mid ] == x :
1110 return mid
12-
13- # If x is greater, ignore left half
14- elif arr [mid ] < x :
15- 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
16-
17- # If x is smaller, ignore right half
18- elif x < arr [mid ]:
19- r = mid - 1 #r is initialised to the leftmost element of the middle so that the search goes till there only the next time
20-
11+
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 )
16+
17+ # Else the element can only be present in right subarray
18+ else :
19+ return binary_search (arr , mid + 1 , r , x )
20+
2121 # If we reach here, then the element was not present
2222 return - 1
2323
You can’t perform that action at this time.
0 commit comments