Algorithms can be expressed in many ways. Here is a concise description of the search algorithm that we have already discussed.
In order to search for a valueNotice that such a description of an algorithm embodies both the steps that need to be carried out and the reason why this gives a correct solution to the problem. This way of describing algorithms is very common when we don't intend to run them in a computer. When we do, further refinement is necessary. A next step in the refinement could be:in a binary search tree
, proceed as follows. If
is empty then
doesn't occur in
and hence we stop. Otherwise, if
is equal to the root of
then
does occur in
and hence we again stop. If, on the other hand,
is smaller than the root, then, by definition of binary search tree, it is enough to search on the left subtree of
. Hence replace
by its left subtree and carry on in the same way. The case in which
is bigger than the root is handled in a similar way.
boolean isin(value v, tree t) {
if (t is empty)
return False;
else
if (v is equal to the root node of t)
return true;
else
if (v < root node of t)
return isin(v, left subtree of t);
else
return isin(v, right subtree of t);
}
This is another example of a recursive algorithm. The recursion
eventually terminates, because every recursive call takes a smaller
tree, so that we eventually find what we are looking for or reach an
empty tree. In this example, the recursion is easily transformed into
a while-loop:
boolean isin(value v, tree t) {
while (t is not empty and v is different from the root of t)
if (v < root node of t)
t = left subtree of t;
else
t = right subtree of t;
if (t is empty)
return false;
else
if (v is equal to the root of t)
return true;
else
return false;
}
Using boolean expressions, the part below the while-loop can be
simplified to
return ((t is not empty) and (v is equal to the root of t));The idea is that each of the expressions is evaluated to a boolean value, then its logical conjunction (``and'') is taken, and finally the obtained truth value is returned.