forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindMaxRecursion.java
More file actions
37 lines (34 loc) · 1.06 KB
/
FindMaxRecursion.java
File metadata and controls
37 lines (34 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.examplehub.maths;
public class FindMaxRecursion {
/**
* Find max value in array using recursion.
*
* @param numbers the numbers to find.
* @param length the length of array.
* @return max value in given array.
*/
public static int max(int[] numbers, int length) {
if (length == 1) {
return numbers[0];
}
int temp = max(numbers, length - 1);
return Math.max(numbers[length - 1], temp);
}
/**
* Find max value in array using recursion.
*
* @param numbers the numbers to find.
* @param left the left index of sub array.
* @param right the right index of sub array.
* @return max value in given array.
*/
public static int max(int[] numbers, int left, int right) {
if (left == right) {
return numbers[left];
}
int middle = MiddleIndexCalculate.middle(left, right);
int leftMax = max(numbers, left, middle); /* find max in range[left, middle] */
int rightMax = max(numbers, middle + 1, right); /* find max in range[middle + 1, right] */
return Math.max(leftMax, rightMax);
}
}