Problems
Problem :
In binary search, we split the data set in half at each recursive call.
One could imagine an algorithm that split the data set up into three or
four sets at each recursive call. Provide an argument why, in Big-O
notation, binary search is as efficient as ternary search or quaternary
search.
Ternary search would result in $O(log3 n)$ and quaternary search would
result in $O(log4 n)$. $(logx a)/(logy a) == x/y$. Therefore the
efficiency of ternary search and quaternary search are only a constant
multiple of binary search, and thus in Big-O notation, they would all be
$O(log n)$.
Problem :
Why is linear search better implemented iteratively rather than recursively?
Linear search is just as easily implemented iteratively as it is
recursively. The recursive version is also less efficient in terms of
system resources, taking up a good deal of space on the call stack since
the function is called once for every data element searched.
Problem :
You have an array of ints sorted in ascending order. Write a function
that recursively does a ternary search (splits the data into three sets
instead of two) on the array.
int ternary_search(int arr[], int find, int low, int high)
{
int middle1 = (low + high)/3;
int middle2 = 2*(low + high)/3;
if (start > finish) return -1;
if (find < arr[middle1]) {
return ternary_search(arr, find, low, middle1);
} else if (arr[middle1] < find && find < arr[middle2]) {
return ternary_search(arr, find, middle1, middle2);
} else if (arr[middle2] < find) {
return ternary_search(arr, find, middle2, high);
} else if (arr[middle1] == find) {
return middle1;
} else {
return middle2;
}
}
Problem :
Your boss tells you to write a function to search for a number in an
unbounded array (the array starts at index 0 but goes on forever). He
tells you to use the standard binary search algorithm. Explain to him
why you can't.
Binary search requires an upper bound. If there is no upper bound, ie. the
set continues on forever, than there is no way to determine what half of
the set is (half of infinity is still infinity).
Problem :
In a last attempt to show how smart he is, your boss tells you to implement
linear search recursively as that is much more efficient than an iterative
implementation. Explain to him why he is incorrect.
A recursive solution would require a relatively expensive function call for
each data element examined, while the iterative version requires only one
function call, which means a constant amount of stack space.