'How can I get minimum number by Recursion in java
I have something error in my java code.. I'm trying to find the minimum number by recursion.. My error in last index.. I noted if the minimum number in last index I get error message "java.lang.ArrayIndexOutOfBoundsException: 8". otherwise, if the minimum number isn't in last index, it return the first minimum number found in the array and never check other values.
This is my code:
public static int minimumElement(int [] nums,int i){
if (i < nums.length && nums[i] < nums[i+1] )
return nums[i];
else
return minimumElement(nums, i=i+1);
}
Outputs
Solution 1:[1]
if (i < nums.length && nums[i] < nums[i+1] )
return nums[i];
Let's say nums.length = 20 and i = 19. Then nums[19 + 1] will be 21st element inside nums which can't exist in the array, hence you get the error.
Solution 2:[2]
I found the answer.
//int mini = nums[0]; "I wrote it in main"
public static int minimumElement(int [] nums,int mini, int i){
if (i >= nums.length-1)
return mini;
if (mini > nums[i+1] )
mini = nums[i+1];
return minimumElement(nums, mini, i=i+1);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | curiousdev |
| Solution 2 | Han |
