Skip to content

Commit 5043f89

Browse files
Find max and min value by recursion
1 parent ff6b5c7 commit 5043f89

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

Maths/FindMaxRecursion.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Maths;
2+
3+
public class FindMaxRecursion {
4+
public static void main(String[] args) {
5+
int[] array = {2, 4, 9, 7, 19, 94, 5};
6+
int low = 0;
7+
int high = array.length - 1;
8+
9+
System.out.println("max value is " + max(array, low, high));
10+
}
11+
12+
/**
13+
* Get max of array using divide and conquer algorithm
14+
*
15+
* @param array contains elements
16+
* @param low the index of the first element
17+
* @param high the index of the last element
18+
* @return max of {@code array}
19+
*/
20+
public static int max(int[] array, int low, int high) {
21+
if (low == high) {
22+
return array[low]; //or array[high]
23+
}
24+
25+
int mid = (low + high) >>> 1;
26+
27+
int leftMax = max(array, low, mid); //get max in [low, mid]
28+
int rightMax = max(array, mid + 1, high); //get max in [mid+1, high]
29+
30+
return leftMax >= rightMax ? leftMax : rightMax;
31+
}
32+
}

Maths/FindMinRecursion.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Maths;
2+
3+
public class FindMinRecursion {
4+
public static void main(String[] args) {
5+
int[] array = {2, 4, 9, 7, 19, 94, 5};
6+
int low = 0;
7+
int high = array.length - 1;
8+
9+
System.out.println("min value is " + min(array, low, high));
10+
}
11+
12+
/**
13+
* Get min of array using divide and conquer algorithm
14+
*
15+
* @param array contains elements
16+
* @param low the index of the first element
17+
* @param high the index of the last element
18+
* @return min of {@code array}
19+
*/
20+
public static int min(int[] array, int low, int high) {
21+
if (low == high) {
22+
return array[low]; //or array[high]
23+
}
24+
25+
int mid = (low + high) >>> 1;
26+
27+
int leftMin = min(array, low, mid); //get min in [low, mid]
28+
int rightMin = min(array, mid + 1, high); //get min in [mid+1, high]
29+
30+
return leftMin <= rightMin ? leftMin : rightMin;
31+
}
32+
}

0 commit comments

Comments
 (0)