Find the minimum value in an array by recursive method
Problem:
Write a recursive function recursiveMinimum that takes an
integer array and the array size as arguments and returns the smallest
element of the array. The function should stop processing and return when it receives an array of 1 element.
I have solve the problem by following way. But there is a problem in the output. Please help me for proper output.
Here is my code:
int recursiveMinimum (int a[],intsize )
{
a = ii;
size = a.length;
if ( size == 1 ) // base case
return a[0] ;
else
{// general case
int y = Minimum ( a, size - 1 );
if ( y < a [size - 1] )
return y ;
else
return a[ size -1 ] ;
}
}//end recursiveMinimum()
That problem would be solved like that in Prolog, but not in Java. Does your teacher expect you to create a new array for every recursive call? It would be better if you passed an index (if you have to do it recursively).Kind regards, Levi
So something likepublic class Test {
public static void main (String[] parameters) {
System.out.println (findMin (new int[] {
4,
1,
2,
5,
3
}));
}
// driver
private static int findMin (int[] array) {
if ((array == null) || (array.length == 0)) {
throw new IllegalArgumentException ("No valid array");
}
return findMinR (array, array.length - 1);
}
// recursive method
private static int findMinR (int[] array, int index) {
return (index == 0) ? array[index] : Math.min (array[index], findMinR (array, index - 1));
}
}
> Write a recursive function recursiveMinimum that takes
> an integer array and the array size as arguments and
> returns the smallest element of the array
I think that the approach you actually want to take is to divide the array into two halves and call the function recursively for each half. At some point you'll get "halves" that contain a single element each, so can compare these.
It's sort've like a binary search, except that it isn't :-) I'm guessing that it's the predecessor assignment for some sort of sorting algorithm.
This should do it.
public static int minValue(int[]numbers,int index){
if (index + 1 == numbers.length){
return numbers[element];
}else{
return Math.min(numbers[index], minValue(numbers,index +1));
}
}