-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxMinDivideAndConquer.java
More file actions
57 lines (45 loc) · 1.56 KB
/
MaxMinDivideAndConquer.java
File metadata and controls
57 lines (45 loc) · 1.56 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
public class MaxMinDivideAndConquer {
static class Pair {
int max;
int min;
}
static Pair findMaxMin(int[] arr, int low, int high) {
Pair result = new Pair();
if (low == high) {
result.max = arr[low];
result.min = arr[low];
return result;
}
if (high == low + 1) {
if (arr[low] > arr[high]) {
result.max = arr[low];
result.min = arr[high];
} else {
result.max = arr[high];
result.min = arr[low];
}
return result;
}
int mid = low + (high - low) / 2;
Pair leftResult = findMaxMin(arr, low, mid);
Pair rightResult = findMaxMin(arr, mid + 1, high);
result.max = Math.max(leftResult.max, rightResult.max);
result.min = Math.min(leftResult.min, rightResult.min);
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter array elements separated by spaces:");
String input = scanner.nextLine();
String[] numStrings = input.split(" ");
int[] arr = new int[numStrings.length];
for (int i = 0; i < numStrings.length; i++) {
arr[i] = Integer.parseInt(numStrings[i]);
}
Pair maxMin = findMaxMin(arr, 0, arr.length - 1);
System.out.println("Max: " + maxMin.max);
System.out.println("Min: " + maxMin.min);
scanner.close();
}
}