iterative binary search python
def binary_search(a, key):
low = 0
high = len(a) - 1
while low < high:
mid = (low + high) // 2
if key == a[mid]:
return True
elif key < mid:
high = mid - 1
else:
low = mid + 1
return False
iterative binary search python
def binary_search(a, key):
low = 0
high = len(a) - 1
while low < high:
mid = (low + high) // 2
if key == a[mid]:
return True
elif key < mid:
high = mid - 1
else:
low = mid + 1
return False
Implement a binary search of a sorted array of integers Using pseudo-code.
# Here's the pseudocode for binary search, modified for searching in an array. The inputs are the array, which we call array; the number n of elements in array; and target, the number being searched for. The output is the index in array of target:
1.Let min = 0 and max = n-1.
2. Compute guess as the average of max and min, rounded down (so that it is an integer).
3. If array[guess] equals target, then stop. You found it! Return guess.
4. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
5. Otherwise, the guess was too high. Set max = guess - 1.
6. Go back to step 2.
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us