Write TWO recursive methods. One to find the maximum in an array, the other to f
ID: 3856971 • Letter: W
Question
Write TWO recursive methods. One to find the maximum in an array, the other to find the minimum. JAVA
public class Lab
{
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
//need help here
{
if (n<1){
return A[0];
}
if (FindMax(A, n-1)> A[n]){
return 1;
}
else {
return A[n];
}
}
public static int FindMin(int A[], int n)
//n is the index of the last element in the array
//need help here
{
if (n<1){
return A[0];
}
if (FindMin(A, n-1)> A[n]){
return 1;
}
else {
return A[n];
}
}
}
Explanation / Answer
The problem is in mainly two parts of the code:
1. if (FindMax(A, n-1)> A[n]){
return 1;
Here, rather than returning 1, we have to return the greater of the two values.
2. if (FindMin(A, n-1)> A[n]){
return 1;
}
Similarly here, rather than returning 1, we have to return the lesser of two values.
Below is the corrected code, along with detailed explaination in the comments itself.
public class Lab
{
public static void main (String []args)
{
int A[] = {2,5,7,-4,6,3};
System.out.println(FindMax(A,5));
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
{
if (n<1){
return A[0];
}
if (FindMax(A, n-1)> A[n]){
return FindMax(A,n-1); //problem was in this line
//Here, rather than returning value "1", we have to pass the greater of two values(as we are finding max)
// Here, if FindMax(A,n-1) is greather than(>) A[n], then pass that value
}
else {
//Else, if the value of A[n] is greater than FindMax(A,n-1), the return the value of A[n]
return A[n];
}
}
public static int FindMin(int A[], int n)
//n is the index of the last element in the array
{
if (n<1){
return A[0];
}
if (FindMin(A, n-1)< A[n]){
return FindMin(A,n-1); //Similar to the above, the problem was in this line of code
//Here, rather than returning value "1", we have to pass the lesser of two values(as we are finding min)
// Here, if FindMin(A,n-1) is lesser than(<) A[n], then pass that value
}
else {
//Else, if the value of A[n] is lesser than FindMin(A,n-1), the return the value of A[n]
return A[n];
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.