0

I need to get the count of numbers less than the first integer in an array using recursion. I am given a function definition as

public static int countGreaterThanFirst(int[]
numbers, int startIndex, int endIndex, int firstNumber){}

I am not supposed to use a loop or global/static variable. How can I convert my implementation below to satisfy the two conditions above. I have recently asked another similar question but this is a bit different due to the need to keep track of the count variable. If someone can help, I will really appreciate. Below is my implementation with a loop.

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    int greater_than_first = 0;
    for (int count = startIndex; count <= endIndex; count++) {
        if (numbers[count] > firstNumber) {
            greater_than_first++;
        }
    }
    return greater_than_first;
}
1
  • It works, but that's not the expected implementation. Commented Mar 29, 2016 at 14:10

2 Answers 2

3

Probably you don't need that much parameters:

public static int countGreaterThanFirst(int[] numbers, int currentIndex) {
    if (currentIndex == numbers.length) return 0;
    else {
        if (numbers[currentIndex] > numbers[0]) {
            return 1 + countGreaterThanFirst(numbers, currentIndex + 1);
        } else {
            return countGreaterThanFirst(numbers, currentIndex + 1);
        }
    }
}

and you should invoke it with (for example):

 countGreaterThanFirst(someArray, 1);

If you meant to find "all the numbers between numbers[startIndex] and numbers[endIndex] that are greater than firstNumber, then the implementation should be pretty similar to the above one:

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex > endIndex) return 0;
    else {
        if (numbers[startIndex] > firstNumber) {
            return 1 + countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber);
        } else {
            return countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber);
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

The parameters is a condition.
Yes, and I have to implement the function as per the definition given
unfortunately, the count is always 0.
How do you invoke it? Why don't you try to debug it at the least? It works fine on my environment.
@ Konstantin thanks for your help. It is working. I was invoking it wrongly.
|
0
public static int doCount(int[] list) {
    if (list.length == 0) {
        return 0;
    }
    return 1 + doCount(Arrays.copyOfRange(list, 1, list.length));
}

Comments

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.