-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxElements.java
More file actions
53 lines (44 loc) · 1.37 KB
/
Copy pathMaxElements.java
File metadata and controls
53 lines (44 loc) · 1.37 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
import java.util.Arrays;
import java.util.Random;
public class MaxElements {
static int[] findTwoMaxElements(int[] arr) {
if (arr.length <= 2) return arr;
int cmps = 0;
int max = arr[0];
int secondMax = arr[1];
if (secondMax > max) {
int temp = max;
max = secondMax;
secondMax = temp;
}
cmps++;
for (int i = 2; i < arr.length; i++) {
cmps++;
if (arr[i] >= secondMax) {
secondMax = arr[i];
cmps++;
if (secondMax > max) {
int temp = max;
max = secondMax;
secondMax = temp;
}
}
}
System.out.printf("Comparisons: %d\n", cmps);
return new int[]{secondMax, max};
}
public static void main(String[] args) {
int size = 1000;
int[] arr = new int[size];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(size * 2);
// arr[i] = arr.length - i;
}
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(findTwoMaxElements(arr)));
Arrays.sort(arr);
System.out.println(arr[arr.length - 1]);
System.out.println(arr[arr.length - 2]);
}
}