Write two recursive methods. One to find the maximum in an array, the other to f
ID: 3729156 • Letter: W
Question
Write two recursive methods. One to find the maximum in an array, the other to find the minimum.
public class Lab14Num1
{
public static void main (String []args)
{
int A[] = {2,5,7,-4,6,3};
System.out.println(FindMax(A,5)); //n is the index of the last element in the array
System.out.println(FindMin(A,5));
}
public static int FindMax(int A[], int n)
//n is the index of the last element in the array
{
}
public static int FindMin(int A[], int n)
//n is the index of the last element in the array
{
}
}
Explanation / Answer
/*SAMPLE OUTPUT
7
-4
*/
class Main{
public static void main (String []args)
{
int A[] = {2,5,7,-4,6,3};
System.out.println(FindMax(A,5)); //n is the index of the last element in the array
System.out.println(FindMin(A,5));
}
public static int FindMax(int A[], int n)
//n is the index of the last element in the array
{
// keeping max in first index, so returning when all are done
if(n == 1)
return A[0];
// if first value is less than n'th value, swapping to have maximum in first index
if(A[0] < A[n-1])
{
int temp = A[0];
A[0] = A[n-1];
A[n-1] = temp;
}
// calling recursively with 1 less
return FindMax(A,n-1);
}
public static int FindMin(int A[], int n)
//n is the index of the last element in the array
{
// keeping min in first index, so returning when all are done
if(n == 1)
return A[0];
// if first value is greater than n'th value, swapping to have minimum in first index
if(A[0] > A[n-1])
{
int temp = A[0];
A[0] = A[n-1];
A[n-1] = temp;
}
// calling recursively with 1 less
return FindMin(A,n-1);
}
}
/*SAMPLE OUTPUT
7
-4
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.