forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindMinMax2.java
53 lines (48 loc) · 1.05 KB
/
FindMinMax2.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/FindMinMax.php.html
*/
package com.dsalgo;
public class FindMinMax2
{
public static void main(String[] args)
{
int[] arr = {4, 3, 5, 1, 2, 6, 9, 2, 10, 11, 12};
MinMax result = findMinMaxRecursive(arr, 0, arr.length - 1);
System.out.println("maximum= " + result.max);
System.out.println("minimum= " + result.min);
}
private static MinMax findMinMaxRecursive(int[] arr, int i, int j)
{
if (i > j)
return null;
if (i == j)
return new MinMax(arr[i], arr[i]);
else
{
MinMax left;
MinMax right;
left = findMinMaxRecursive(arr, i, (i + j) / 2);
right = findMinMaxRecursive(arr, (i + j) / 2 + 1, j);
if (left == null)
return right;
else if (right == null)
return left;
else
{
return new MinMax(Math.min(left.min, right.min), Math.max(
left.max, right.max));
}
}
}
}
class MinMax
{
public int min;
public int max;
public MinMax(int min, int max)
{
this.min = min;
this.max = max;
}
}