Answered step by step
Verified Expert Solution
Question
1 Approved Answer
RECURSION-Write a method that uses a divide-and-conquer strategy to find the maximum value in an integer array. The maximum value of a one-element array is
RECURSION-Write a method that uses a divide-and-conquer strategy to find the maximum value in an integer array. The maximum value of a one-element array is that element. The maximum of any other array is the maximum of the left half, or the maximum of the right half, whichever is larger. (You can use ArraySum as a starting point.)
public static void main(String[] args) { int[] test = {3, 4, 5, 1, 2, 3, 2}; // sum should be 20 int result = arraySum(test); System.out.println(result); } /** * Returns the sum of all array elements. */ public static int arraySum(int[] arr) { return arraySumRec(arr, 0, arr.length - 1); } /** * Returns the sum of array elements from start to end, inclusive. */ private static int arraySumRec(int[] arr, int start, int end) { if (start == end) { return arr[start]; } else { int mid = (start + end) / 2; int leftSum = arraySumRec(arr, start, mid); int rightSum = arraySumRec(arr, mid + 1, end); return leftSum + rightSum; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started