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
image of first minimum number found in the array
image of minimum number in last index
CodePudding user response:
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.
CodePudding user response:
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);
}