#include
using namespace std;
int g(float A[] , int L , int H)
{
if (L==H)
if (A[L] > 0.0)
return 1;
else
retu
and M = 1 since it its a int -return g(A,0,3) + g(A,2 3)
Here is first problem. If M = 1, then how do you say it's return g(A,0,3) + g(A,2, 3)
?
It should be:
return g(A,0,1) + g(A,2, 3)
//^ this should be 1
And since you're wrong at the first step, all the consecutive steps will be wrong.
My suggestion would be :
g(A,0,3);
. This is the first call.g(A,0,1)
as the left node, and g(A,2,3)
as right node.if
condition becomes true.if
condition becomes true, stop making new nodes (in that branch), and go up towards the root node, summing the values of nodes which you meet on the way.main()
.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:
{-1.5, 3.1, -5.2, 0.0}
0 1 2 3
L H
then since L=0
and H=3
, M = (0+3)/2 = 3/2 = 1
when you get to g(A, L, M) + g(A, M+1, H)
, you branch into two:
{-1.5, 3.1, -5.2, 0.0}
0 1 2 3
L H
L1 H1 L2 H2
let's do the left part g(A, L1, H1) = g(A, 0, 1)
first:
{-1.5, 3.1, -5.2, 0.0}
0 1 2 3
L H
L1 H1 L2 H2
^^^^^^^
again since L1=0
, H1=1
, and so M1 = (0+1)/2 = 1/2 = 0
and you branch into two again g(A, 0, 0)
and g(A, 1, 1)
:
{-1.5, 3.1, -5.2, 0.0}
0 1 2 3
L H
L1 H1 L2 H2
L11,H11 L12,H12
on the left part, since -1.5 <= 0
therefore g(A, L11, H11) = g(A, 0, 0) = 0
, on the right part, since 3.1 > 0
therefore g(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 that g(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:
{-1.5, 3.1, -5.2, 0.0}
At the second layer of iteration, you split the array into two:
{-1.5, 3.1, -5.2, 0.0}
/ \
/ \
/ \
/ \
{-1.5, 3.1} {-5.2, 0.0}
At the third layer, you split again:
{-1.5, 3.1, -5.2, 0.0}
/ \
/ \
/ \
/ \
{-1.5, 3.1} {-5.2, 0.0}
/ \ / \
/ \ / \
{-1.5} {3.1} {-5.2} {0.0}
At this point L==H
so, we can evaluate the nodes:
{-1.5, 3.1, -5.2, 0.0}
/ \
/ \
/ \
/ \
{-1.5, 3.1} {-5.2, 0.0}
/ \ / \
/ \ / \
{-1.5} {3.1} {-5.2} {0.0}
| | | |
0 1 0 0
and to find the return values, we sum up:
{-1.5, 3.1, -5.2, 0.0}
/ \
/ \
/ \
/ \
{-1.5, 3.1} {-5.2, 0.0}
0+1=1 0+0=0
and lastly
{-1.5, 3.1, -5.2, 0.0}
1+0=1