Next, we consider a recursive algorithm for a binary search within a sorted list of items. Suppose
represent a list of
items sorted by a numeric key in descending order. The
item is denoted
and its key value by
For example, each item might contain data on the buildings in a city and the key value might be the height of the building. Then
would be the item for the tallest building and
would be its height. The algorithm
can be applied to search for an item in
with key value
This would be accomplished by the execution of
When the algorithm is completed, the variable
will have a value of
if an item with the desired key value was found, and the value of
will be the index of an item whose key is
If
keeps the value
no such item exists in the list. The general idea behind the algorithm is illustrated in
Figure 8.1.6
In the following implementation of the Binary Search in SageMath, we search within a sorted list of integers. Therefore, the items themselves are the keys.