You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Binary Search Algorithm: The basic steps to perform Binary Search are:
Begin with the mid element of the whole array as a search key.
If the value of the search key is equal to the item then return an index of the search key.
Or if the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half.
Repeatedly check from the second point until the value is found or the interval is empty.
defbinarySearch(arr, l, r, x):
# Check base caseifr>=l:
mid=l+ (r-l) //2# If element is present at the middle itselfifarr[mid] ==x:
returnmid# If element is smaller than mid, then it# can only be present in left subarrayelifarr[mid] >x:
returnbinarySearch(arr, l, mid-1, x)
# Else the element can only be present# in right subarrayelse:
returnbinarySearch(arr, mid+1, r, x)
else:
# Element is not present in the arrayreturn-1
Iterative approach
defbinarySearch(v, To_Find):
lo=0hi=len(v) -1# This below check covers all cases , so need to check# for mid=lo-(hi-lo)/2whilehi-lo>1:
mid= (hi+lo) //2ifv[mid] <To_Find:
lo=mid+1else:
hi=midifv[lo] ==To_Find:
print("Found At Index", lo)
elifv[hi] ==To_Find:
print("Found At Index", hi)
else:
print("Not Found")
The text was updated successfully, but these errors were encountered:
Binary Search Algorithm: The basic steps to perform Binary Search are:
Pseudocode
Recursive appraoch
Iterative approach
The text was updated successfully, but these errors were encountered: