# recursion 1
def binsearch(lo, hi, list, key):
if lo > hi:
return False
p = ( lo + hi ) >> 1
if key == list[p]:
return True
if key > list[p]:
return binsearch(p+1, hi, list, key)
else:
return binsearch(lo, p - 1, list, key)
# recursion 2
def _binsearch(lo, hi, list, key):
if lo <= hi:
p = ( lo + hi ) >> 1
if key == list[p]:
return True
if key > list[p]:
return binsearch(p+1, hi, list, key)
else:
return binsearch(lo, p - 1, list, key)
return False
#iteration 1
def _binsearch_(lo, hi, list, key):
pos = False
while lo <= hi:
p = (lo + hi ) >> 1
if list[p] == key:
pos = True
break
elif key > list[p]:
lo = p + 1
else:
hi = p - 1
return pos
#iteration 2
def _binsearch_2(lo, hi, list, key):
pos = False
while not lo > hi and pos is False:
p = (lo + hi ) >> 1
if list[p] == key:
pos = True
elif key > list[p]:
lo = p + 1
else:
hi = p - 1
return pos
def searchBin(list, key):
return _binsearch_2(0, len(list)-1, list, key)
# non recursion => iteration
def main():
list = [-3,-1,11,22,44,55,77,88,101]
print(list)
key = -3
if searchBin(list,key) is True:
print(f'{key} exists in List')
else:
print(f'{key} not exist in List')
main()
IyByZWN1cnNpb24gMQpkZWYgYmluc2VhcmNoKGxvLCBoaSwgbGlzdCwga2V5KToKICAgIGlmIGxvID4gaGk6CiAgICAgICByZXR1cm4gRmFsc2UKICAgIHAgPSAoIGxvICsgaGkgKSA+PiAxCiAgICBpZiBrZXkgPT0gbGlzdFtwXToKICAgICAgIHJldHVybiBUcnVlCiAgICBpZiBrZXkgPiBsaXN0W3BdOgogICAgICAgcmV0dXJuIGJpbnNlYXJjaChwKzEsIGhpLCBsaXN0LCBrZXkpCiAgICBlbHNlOgogICAgICAgcmV0dXJuIGJpbnNlYXJjaChsbywgcCAtIDEsIGxpc3QsIGtleSkKCiMgcmVjdXJzaW9uIDIKZGVmIF9iaW5zZWFyY2gobG8sIGhpLCBsaXN0LCBrZXkpOgogICAgaWYgbG8gPD0gaGk6CiAgICAgIHAgPSAoIGxvICsgaGkgKSA+PiAxCiAgICAgIGlmIGtleSA9PSBsaXN0W3BdOgogICAgICAgICAgcmV0dXJuIFRydWUKICAgICAgaWYga2V5ID4gbGlzdFtwXToKICAgICAgICAgIHJldHVybiBiaW5zZWFyY2gocCsxLCBoaSwgbGlzdCwga2V5KQogICAgICBlbHNlOgogICAgICAgICAgcmV0dXJuIGJpbnNlYXJjaChsbywgcCAtIDEsIGxpc3QsIGtleSkKICAgIHJldHVybiBGYWxzZQoKI2l0ZXJhdGlvbiAxCmRlZiBfYmluc2VhcmNoXyhsbywgaGksIGxpc3QsIGtleSk6CiAgICBwb3MgPSBGYWxzZQogICAgd2hpbGUgbG8gPD0gaGk6CiAgICAgICAgcCA9IChsbyArIGhpICkgPj4gMQogICAgICAgIGlmIGxpc3RbcF0gPT0ga2V5OgogICAgICAgICAgICBwb3MgPSBUcnVlCiAgICAgICAgICAgIGJyZWFrCiAgICAgICAgZWxpZiBrZXkgPiBsaXN0W3BdOgogICAgICAgICAgICBsbyA9IHAgKyAxCiAgICAgICAgZWxzZToKICAgICAgICAgICAgaGkgPSBwIC0gMQogICAgcmV0dXJuIHBvcwoKI2l0ZXJhdGlvbiAyCmRlZiBfYmluc2VhcmNoXzIobG8sIGhpLCBsaXN0LCBrZXkpOgoKICAgIHBvcyA9IEZhbHNlCiAgICB3aGlsZSBub3QgbG8gPiBoaSBhbmQgcG9zIGlzIEZhbHNlOgogICAgICAgIHAgPSAobG8gKyBoaSApID4+IDEKICAgICAgICBpZiBsaXN0W3BdID09IGtleToKICAgICAgICAgICAgcG9zID0gVHJ1ZQogICAgICAgIGVsaWYga2V5ID4gbGlzdFtwXToKICAgICAgICAgICAgbG8gPSBwICsgMQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIGhpID0gcCAtIDEKICAgIHJldHVybiBwb3MKCgpkZWYgc2VhcmNoQmluKGxpc3QsIGtleSk6CiAgICByZXR1cm4gX2JpbnNlYXJjaF8yKDAsIGxlbihsaXN0KS0xLCBsaXN0LCBrZXkpCgojIG5vbiBy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