Learn-dsa..in 30 days!



























CC-6 : Find max and min number.

Description:

Given an input array of numbers, find the maximum and minimum numbers.

Test cases and expected outputs:

Input Parameters Expected outputs
Original Array: : 1,2,3,4,5,6,7,1 Min element of array: 1
Max element of array: 7

Pseudocode:

findMin(num):

The array arr to be checked is received as input parameter.
If num==1, return arr[0]; (base case).
Recursively call findMin() with parameter arr[num-1] and then find the lesser value from return value from recursive call and num-1. Return the lesser value found from the current recursive method call.

findMax(num):

The array arr to be checked is received as input parameter.
If num==1, return arr[0]; (base case).
Recursively call findMax() with parameter arr[num-1] and then find the greater value from return value from recursive call and num-1. Return the greater value found from the current recursive method call.

Code:

public int findMin(int[] arr, int n) throws Exception{
	if (n==1) {
		return arr[0];
	}
	return 	Math.min(arr[n-1], findMin(arr,n-1));
}

public int findMax(int[] arr, int n) throws Exception{
	if (n==1) {
		return arr[0];
	}
	return 	Math.max(arr[n-1], findMax(arr,n-1));
}

Click here to download and run code and test cases !