-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathLarThreeElements.java
44 lines (40 loc) · 1.24 KB
/
LarThreeElements.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
/* Find the largest three elements in the array.
* One solution: Sort the array and get the last
* three elements in the array.
* This solution: Does it in single pass.
*/
package arrays;
public class LarThreeElements extends Stub {
public static void getLarThreeElement(int[] input) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
int thirdLargest = Integer.MIN_VALUE;
if (input != null && input.length != 0) {
for (int idx = 0; idx < input.length; idx++) {
if (input[idx] > largest) {
thirdLargest = secondLargest;
secondLargest = largest;
largest = input[idx];
}
else if (input[idx] > secondLargest) {
thirdLargest = secondLargest;
secondLargest = input[idx];
}
else if (input[idx] > thirdLargest) {
thirdLargest = input[idx];
}
}
print("Largest", largest);
print("2nd Largest", secondLargest);
print("3rd Largest", thirdLargest);
if (secondLargest == Integer.MIN_VALUE || thirdLargest == Integer.MIN_VALUE) {
printStringArray("Input does not have either second or third largest value");
}
}
}
public static void main(String[] args) {
int[] input = generateArray(10, 20);
printArray("Input", input);
getLarThreeElement(input);
}
}