0

Whole problem: Given an array A indexed from 1 to n containing integers, determine how many integers in A[1 to n] are greater than A[1]

What i've wrote so far:

static int numGreater(int A[], int n, int count)
{
    if(A[1] == A[n])
    {
        return count; 
    }
    else 
    {
        count = (A[1] < A[n] ? count : + 1);
        return numGreater(A, n - 1, count);
    }
}

Kinda got stumped. Still new to coding in recursions.

11
  • 2
    What's stumping you? Errors? I can see a few logical errors. Commented Aug 28, 2016 at 17:14
  • What is the if expression supposed to do, and why do you think that expression does that? Commented Aug 28, 2016 at 17:17
  • Is that the required method signature or did you come up with it? I would try to think how to do it without passing count around; might help to think recursively. Commented Aug 28, 2016 at 17:28
  • Sorry if my code is a bit illogical. The if condition should stop the repetition of the method when the int n equates to the first index. Commented Aug 28, 2016 at 17:28
  • 1
    Why is recursion requested in this case? It doesn't really make the algorithm more "elegant" or readable than a simple for loop in this situation and it will be far less performant. Commented Aug 28, 2016 at 19:32

3 Answers 3

1

I've finally got it. Problem is that, well, I know there's a way that I dont have to put "count" on the parameters, but I don't know how to. What I did was.

static int numGreater(int A[], int n, int count)
{
    if (n <= 1)
    {
        return count;
    }
    else
    {
        count = A[1] < A[n] ? count + 1 : count;
    return numGreater(A, n - 1, count);
    }
}

I'm pretty sure there are better ways to do this, and I still want to know them to broaden my understanding on recursions. Further answers would be appreciated.

Sign up to request clarification or add additional context in comments.

2 Comments

Good job figuring it out on your own!
Thanks man. :D i'll still try to do what you suggested before. The one that doesn't need a "count" in the parameters. Thanks for the help too.
1

Since you've answered it yourself, I'll add my 2-bits with a little visual explanation on how you can avoid retaining the count in a variable and passing it as a parameter in your recursive method.

Discalimer: I'm using Java's array indexing convention since problem statements like yours may not be language specific and indexing a Java array from 1-n as opposed to 0-(n-1) makes little sense due to the extra elements required to do so. With that said, I assume they mean an array consists of n elements which fill the array. I also start at the beginning of the array and work towards the end; there's no difference in this regard because in either case the stack unwinds to return the value to the caller.

My crude drawing below is pretty self-explanatory. The |_..._|s show the values that are being compared with the associated recursive method calls. On the first call we check for the base case and if not met we call the method again with the next index; we continue to do so until we reach the base case (n == A.length). Once we reach the end we return 0 to the previous call which returns its value plus the next call's value (the ongoing count). We continue doing this until we return to the caller.

    0     1     2     3 : indices
    -------------------
    3     5     3     6 : values
    |_____|     |     |
    |___________|     |
    |_________________|
<--------2| <--1| <--1| <--0| : return values
    -------------------------
          1     2     3     4 : call stack (4 = base case)

Here's the code that does just that:

static int numGreater(int[] A, int n) {
    if (n == A.length) return 0;
    return (A[0] < A[n] ? 1 : 0) + count(A, n + 1);
}

Now you should be able to see that each method call that is not the base case will add 1 or 0 to the next call based on the A[0] < A[n] condition thereby accumulating the count as the stack unwinds making the count variable unnecessary.

Note that you should also be able to see why checking for equality between the first and i-th element will not work due to the fact it could short circuit the recursion resulting in an incorrect count.

2 Comments

Somehow I got it. xD I don't know how to explain it myself, but I got it still. I'll probably shift towards working to the end starting from the first index, rather than the one I did. I think most people would read the code easier that way. Thank you for you're answer sir. One question though, with what you said about indexing an array. Is it better to index an array starting from 1-n or 0-n? English isn't my first language so I kinda didnt get that lone statement. Sorry.
@Emanhero, it's best to follow the language. Check out this tutorial; the first thing discussed is the indexing of an array in Java. Doing A[n] on an array with n elements will result in an ArrayIndexOutOfBoundsException since the indices go from 0 to (n-1).
0

Terminate: if n is less than 2 - you have nothing to compare.

Recursive step: if A[n] > A[1] add 1 to the result and call recursive function.

static int numGreater(int A[], int n)
{
    if (n < 2) return 0;
    return A[n] > A[1] 
        ? 1 + numGreater(A, n - 1)
        : numGreater(A, n - 1);
}

4 Comments

return (A[n] > A[1] ? 1 : 0) + numGreater(A, n - 1);; DRY.
That is your rightful opinion which I disagree with. But it wasn't a matter of readability but a matter of needless repetition.
ok, let me be more clear: ?: usage as an intermediate step of computation is bad practice. And it's not only my opinion.
I don't see how that added clarity to your readability claim. Either way, your claim(s) will remain opinion until you back them up with an authoritative source not based on opinion. Doesn't matter if you can show that 1, 100, or 1k people share your opinion because I can do the same; it's still opinion. Saying your snippet has needless repetition by calling the same method twice with the same arguments is fact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.