Write a recursive definition of indexOf from the
first page, for an unsorted Vector. You will need an extra
parameter:
// Don't be intimidated by the size of this solution, it's mostly
// comments.
// First, note that the indexOf method will first be called with 0,
// which means we will start looking with the first element of
// the array:
Vector v;
Item i;
// ... some stuff, then:
v.indexOf(i, 0);
// Now, we can define a recursive search that "shrinks" the size
// of the vector left to search one item at a time.
int Vector::indexOf(Item item, int startIdx) {
// In this function, we have two base cases, corresponding to
// the two possible outcomes of our search
if ( startIdx >= length() ) {
// This is to catch ourselves if we run off the end
// of the vector
return INVALID_INDEX;
} else if ( item.equals( get(startIdx) ) ) {
// This is if we've found the item
return startIdx;
} else {
// Otherwise, we need to search the rest of the vector.
return indexOf(item, startIdx + 1);
}
}
Why is this version less desirable than the iterative
version?
Answer: because each recursive call
will require a new activation record on the stack. Searching
down a 10,000 element vector, for example, will require 10,000
activation records. This takes a lot of memory.