#include <iostream>
using namespace std;
int g(float A[] , int L , int H)
{
if (L==H)
if (A[L] > 0.0)
return 1;
else
return 0;
int M = (L+H)/2;
return g(A,L,M)+ g(A,M+1,H);
}
int main (void)
{
float A[] = {-1.5 ,3.1,-5.2,0.0};
g(A,0,3);
system ("pause");
return 0;
}
its asking me what is return by the function g and what the function does
here is what i got so far
first call is g(A , 0 ,3)
-total skip the IF statement and M = 1 since it its a int
-return g(A,1,3) + g(A,2 3)
second call
– g(A,1,3) skipp the if statement again
– M = 0;
– g(A,2 3) skip the if statement again
– M= 2;
third call
-g(A, 0,0,)
return 0
-g(A,3,3)
return 0;
so it just return 0?
and i am guessing it is dividing the middle value and some sort of binary search?
It’s a convoluted way to count how many numbers in the array is greater than 0. And if you try to run this in a compiler, the return value is 1 because the only number that is greater than 0 in the array is 3.1.
at first run:
then since
L=0andH=3,M = (0+3)/2 = 3/2 = 1when you get tog(A, L, M) + g(A, M+1, H), you branch into two:let’s do the left part
g(A, L1, H1) = g(A, 0, 1)first:again since
L1=0,H1=1, and soM1 = (0+1)/2 = 1/2 = 0and you branch into two againg(A, 0, 0)andg(A, 1, 1):on the left part, since
-1.5 <= 0thereforeg(A, L11, H11) = g(A, 0, 0) = 0, on the right part, since3.1 > 0thereforeg(A, L12, H12) = g(A, 1, 1) = 1.So therefore
g(A, 0, 1) = g(A, 0, 0) + g(A, 1, 1) = 1.Do the same with
g(A, L2, H2), and you get thatg(A, L, H) = g(A, L1, H1) + g(A, L2, H2) = 1 + 0 = 1.@Nawaz had a good idea of visualizing this into a binary tree, basically you start with at the root of the tree:
At the second layer of iteration, you split the array into two:
At the third layer, you split again:
At this point
L==Hso, we can evaluate the nodes:and to find the return values, we sum up:
and lastly