Recursion Question

I have the below start on an issue and am looking for some guidance if you please. I am attempting to count the number of negatives in an array.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   template< typename T>
   T    countNegatives( T * a, int N, int count = 0 )               // a is the name of the array, N is the length of the array
    {     
        if  ( N == 1 ) 
		{
			return count;
		}
		if (a[N] > 0)
		{
			count++;
		}
        else
		{
			count ++;
			return countNegatives(a+1, N-1);
			return  count;
		}      //  (a+1, N-1)  is the rest of the array
    }
I can get it without recursion but I am having difficulties including recursion to increase efficiency. Any help would be appreciated, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	template< typename T>
     T    countNegatives( T * a, int N )               // a is the name of the array, N is the length of the array
    {     
	T  sum = 0;
                     for (int  i = 0;   i  <  N;  i++)
                     {//open for loop   
						 if (a[i] < 0){ 
						 sum  ++;     
					 
						 }
						 else {
						 }
					 
					 }//close for loop    

                     return sum;



}
//- You can't return two values, Pass what you need by reference instead;
//- You are returning T, but I don't see how you actually do this in your function
//- You increment count regardless if if a[N] is positive or negative
//- You quit if N==1, but N doesn't that mean there is still one value left?
//- Check a[N], if the array is 13 long and you refer to a[13], you'll overflow the array.

1
2
3
4
5
6
7
8
9
template< typename T>
int countNegatives( T a[], int N, int &count = 0 ) // passing count by reference.
{     
	if ( N == 0 ) return count;

	if (a[N-1] < 0) count++; // Checks if the last value is negative, if so, increment count

	return countNegatives(a, N-1, count);
}
Last edited on
> int countNegatives( T a[], int N, int &count = 0 ) // passing count by reference.

This will not compile - literal 0 is not a modifiable l-value.


And there is no reason why count has to be passed by reference.

1
2
3
4
5
6
template< typename T >
int countNegatives( const T* a, int N, int count = 0 ) // const-correct
{
    if  ( N == 0 ) return count ;
    else return countNegatives( a+1, N-1, ( a[0]<0 ? count+1 : count ) ) ;
}
1
2
3
4
5
6
7
if(N==0) return 0;
return (a[0]<0) + countNegatives(a+1, N-1);

//or with iterators
if( beg==end ) return 0;
Iter first = beg++;
return (*first<0) + countNegatives(beg, end);


can get it without recursion but I am having difficulties including recursion to increase efficiency.
I don't see how using recursion will increase efficiency.
Well, f[beg; mid) + f[mid;end) (paralellized)
Topic archived. No new replies allowed.