-2

I have a problem want to solve. I have an array of integers from which I want to get the minimum integer. I have also been given a function definition which am supposed to adhere to. I am not supposed to use a loop or a static variable in my solution. How can I solve this? Here is my function.

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

Please assist. I have tried this implementation with a loop.

public static int findMin(int[] numbers, int startIndex, int endIndex) {
    int min = 0;
    for (int count = startIndex; count <= endIndex; count++) {
        if (numbers[count] < min) {
            min = numbers[count];
        }
    }
    return min;
}
1
  • I will put here solution for Java 8 using streams. Just in case: Arrays.asList(numbers).stream().min(Integer::compareTo).get(); Commented Mar 29, 2016 at 13:23

2 Answers 2

1

First thing you should consider when using recursion is the exit state; which means when the function will be exit

 public static int findMin(int[] numbers, int startIndex, int endIndex) {
        if(startIndex == endIndex){
            return numbers[startIndex];
        }
        int min = findMin(numbers, startIndex+1, endIndex);
        return  numbers[startIndex] < min ? numbers[startIndex] : min ;
}
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

int min(int a[]){ //Here you only need to supply the array.
    return min(a, 0, a[0]);
}

int min(int[] a, int i, int min)
{
    if(i==a.length-1)
        return  (a[i]<min)?a[i]:min;
    else
        return min(a, i+1, (a[i]<min)?a[i]:min);
}

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.