about recursion

I need your help please ..

Write a recursive Java function to find the minimum and the maximum element in an array. Verify that your function is correct.

  1. // Recursive Java program to find minimum
    import java.util.*;
    
    class GFG {
    
    	// function to return minimum element using recursion
    	public static int findMinRec(int A[], int n)
    	{
    	// if size = 0 means whole array
    	// has been traversed
    	if(n == 1)
    		return A[0];
    		
    		return Math.min(A[n-1], findMinRec(A, n-1));
    	}
    	
    	// Driver code
    	public static void main(String args[])
    	{
    		int A[] = {1, 4, 45, 6, -50, 10, 2};
    		int n = A.length;
    		
    		// Function calling
    		System.out.println(findMinRec(A, n));
    	}
    }
    
    //This code is contributed by Niraj_Pandey
    • 0
  2. // Recursive Java program to find maximum
    import java.util.*;
    
    class GFG {
    	
    	// function to return maximum element using recursion
    	public static int findMaxRec(int A[], int n)
    	{
    	// if size = 0 means whole array
    	// has been traversed
    	if(n == 1)
    		return A[0];
    		
    		return Math.max(A[n-1], findMaxRec(A, n-1));
    	}
    
    	// Driver code
    	public static void main(String args[])
    	{
    		int A[] = {1, 4, 45, 6, -50, 10, 2};
    		int n = A.length;
    		
    		// Function calling
    		System.out.println(findMaxRec(A, n));
    	}
    }
    
    //This code is contributed by Niraj_Pandey
    • 0
أضف اجابة

أضف اجابة

‫تصفح