Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

programming language is JAVA: The maximum-valued element of an integer -valued a

ID: 3840955 • Letter: P

Question

programming language is JAVA:

The maximum-valued  element of an integer -valued  array can be recursively calculated as follows:

If the array has a single element , that is its maximum (note that a zero-sized array has no maximum)

Otherwise, compare the first element with the maximum of the rest of the array -- whichever is larger is the maximum value .

Write an int  method  named  max that accepts an integer  array , and the number of elements in the array and returns the largest value in the array . Assume the array has at least one element .

Explanation / Answer

Here is code:

public static int max(int[] arr, int length) {
if (length == 1) {
return arr[0];
}
// array length is zero
else if(length == 0)
return -1;
// find the max with current value
return max(arr, length - 1) > arr[length - 1] ? max(arr, length - 1) : arr[length - 1];
}

Sample program to test:

public class Testing {

public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9};
int high = max(arr, arr.length);
System.out.println("Maximum is : " + high);

}

public static int max(int[] arr, int length) {
if (length == 1) {
return arr[0];
}
// array length is zero
else if(length == 0)
return -1;
// find the max with current value
return max(arr, length - 1) > arr[length - 1] ? max(arr, length - 1) : arr[length - 1];
}
}

Output:

Maximum is : 9