I’m adding example code here in Python instead of Java because Python really lets you see how the algorithm works when a type system can be set aside. The recursive implementation:
def search(L, lo, hi, key):
if lo > hi: return -1
mid = (lo + hi) / 2
if L[mid] < key:
# seach left of mid
return search(L, mid + 1, hi, key)
elif L[mid] > key:
# search right of mid
return search(L, lo, mid - 1, key)
else:
return mid
And the iterative implementation:
def search(L, lo, hi, key):
while lo <= hi:
mid = (lo + hi) / 2
if L[mid] < key:
hi = mid - 1
elif L[mid] > key:
lo = mid + 1
else:
return mid
return -1