Binary Search Visualization
How Binary Search Works
Binary Search is an efficient algorithm for searching a sorted array by repeatedly dividing the search interval in half. It works by comparing the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until the target is found or it is clear the target is not in the array.
function binarySearch(array, target):
left = 0
right = array.length - 1
while left <= right:
mid = (left + right) / 2
if array[mid] == target:
return mid
else if array[mid] < target:
left = mid + 1
else:
right = mid - 1
visualize(array, left, mid, right)
return -1