forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeakElement.java
More file actions
62 lines (53 loc) · 1.55 KB
/
PeakElement.java
File metadata and controls
62 lines (53 loc) · 1.55 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
57
58
59
60
61
62
package com.thealgorithms.datastructures.arrays;
/**
* A utility class to find a peak element in an array.
*
* <p>
* A peak element is an element greater than or equal to its neighbors.
*
* Time Complexity: O(log n) using binary search
* Space Complexity: O(1)
*
* Author: https://github.com/VeeruYadav45
*/
public final class PeakElement {
// Private constructor to prevent instantiation
private PeakElement() {
}
/**
* Finds the index of a peak element using binary search.
*
* @param arr the input array
* @return the index of a peak element
*/
public static int findPeakElement(final int[] arr) {
int n = arr.length;
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
boolean leftOk = (mid == 0) || (arr[mid] >= arr[mid - 1]);
boolean rightOk = (mid == n - 1) || (arr[mid] >= arr[mid + 1]);
if (leftOk && rightOk) {
return mid;
}
if (mid > 0 && arr[mid - 1] > arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
/**
* Example usage.
*
* @param args command line arguments (not used)
*/
@SuppressWarnings("PMD.UselessMainMethod")
public static void main(final String[] args) {
int[] arr = {1, 3, 20, 4, 1, 0};
int peakIndex = findPeakElement(arr);
System.out.println("Peak element is " + arr[peakIndex]);
}
}