function search(a, value)
return search(a, value, 0, a.size() - 1); // FIRST RECURSIVE CALL
end
function search(a, value, s, e)
// "a" is an ordered, indexed data structure of type T
// "value" is the value to be matched, of data type T
// "s" is the starting index of range
// "e" is the ending index of range
search fails if s is greater than e OR s < zero OR e >= a's size
if the only way the s can be < zero is programmer error, assert that s >= 0
if the only way that e can be >= a's size is programmer error, assert that e < a's size
otherwise, return -1 to report search failure
int m = index of the middle element, truncated average of s and e
if (value matches am) // got lucky -- matches middle element
return index of the middle element
else if (s == e) // 1-element array
return -1; // only element in range did not match
else if (value less than am) // look between s and m-1
e = m - 1;
else // look between m+1 and e
s = m + 1;
return search(a, value, s, e); // RECURSIVE CALL
end
|