Pedro Rangel's approach to representing binary search is to partition the list into sub lists where the index is redefined . It is very intuitive in the way it represented.
There is another approach that I also find intuitive and more practical in some cases. The idea is to represent the limits of the search using a kind of arrow or pointer to demarcate the boundaries. At each iteration, it is as if these boundaries were being "flattened" or "cut" in half.
Let's see ...
Step 1
Searching 57 . Calculation of the mean: (0 + 12) / 2 = 6
.
0 1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------------------
12 13 15 19 24 28 39 57 59 63 67 69 74
| | |
início meio fim
Step 2
57 is greater than 39 , so move início
to the right element of meio
7
.
Also move the meio
to the result of (7 + 12) / 2 = 9
.
0 1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------------------
12 13 15 19 24 28 39 57 59 63 67 69 74
| | |
início meio fim
Step 3
57 is less than 63 , so move the início
to the left element of meio
8
.
Also move the meio
to the result of (7 + 8) / 2 = 7
.
In this case, início
and meio
will both be in the 7
position.
0 1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------------------
12 13 15 19 24 28 39 57 59 63 67 69 74
| |
início fim
meio
Step 4
As the value of meio
is equal to 57
, we find the result and result of the search is that the element was found at position 7
.