Binary search is a procedure for searching an element in
an array. The array has to be sorted in ascending order.
The basic idea is to compare the middle element of the
array with the element to be found. The comparison can yield three
results:
the middle element is the same as the element to be
found
In this case the search is successful and the returns the index
(field position) of the element to be found.
the middle element is smaller than the element to be
found
The search is continued recursively to the right of
the element.
the middle element is greater than the element to be
found
The search is continued recursively to the left of
the element.
With sorted data the binary search has a complexity of
O(log n).
The animation demonstrates the process of binary searching and shows
the source code. To better understand the procedure the current code
line is highlighted.
Screen Shot(s):
Starting situation after determining middle element
Second comparison - Success!
Return the result - the index of the searched element