Apart from this code being horrible inefficient, is this way I´m writing recursive function here considered “good style”. Like for example what I am doing creating a wrapper then passing it the int mid and a counter int count.
What this code does is getting values from the array then see if that combined with blockIndex is greater than the mid. So, appart from being inefficient would I get a job writing recursive functions like this?
int NumCriticalVotes :: CountCriticalVotesWrapper(Vector<int> & blocks, int blockIndex)
{
int indexValue = blocks.get(blockIndex);
blocks.remove(blockIndex);
int mid = 9;
return CountCriticalVotes(blocks, indexValue, mid, 0);
}
int NumCriticalVotes :: CountCriticalVotes(Vector<int> & blocks, int blockIndex, int mid, int counter)
{
if (blocks.isEmpty())
{
return counter;
}
if (blockIndex + blocks.get(0) >= mid)
{
counter += 1;
}
Vector<int> rest = blocks;
rest.remove(0);
return CountCriticalVotes(rest, blockIndex, mid, counter);
}
This is valid to the extent that it’ll work for sufficiently small collections.
It is, however, quite inefficient — for each recursive call you’re creating a copy of the entire uncounted part of the Vector. So, if you count a vector containing, say, 1000 items, you’ll first create a Vector of 999 items, then another of 998 items, then another of 997, and so on, all the way down to 0 items.
This would be pretty wasteful by itself, but seems to even get worse. You’re then removing an item from your Vector — but you’re removing the first item. Assuming your Vector is something like
std::vector, removing the last item takes constant time but removing the first item takes linear time — i.e., to remove he first item, each item after that is shifted “forward” into the vacated spot.This means that instead of taking constant space and linear time, your algorithm is quadratic in both space and time. Unless the collection involved is extremely small, it’s going to be quite wasteful.
Instead of creating an entire new Vector for each call, I’d just pass around offsets into the existing Vector. This will avoid both copying and removing items, so it’s pretty trivial to make it linear in both time and space (which is still well short of optimum, but at least not nearly as bad as quadratic).
To reduce the space used still further, treat the array as two halves. Count each half separately, then add together the results. This will reduce recursion depth to logarithmic instead of linear, which is generally quite substantial (e.g., for a 1000 items, it’s a depth of about 10 instead of about a 1000. For a million items, the depth goes up to about 20 instead of a million).