How to Find Peak Element in the Array in Java?

Hello Friends Today, through this tutorial, I will tell you How to Find Peak Element in the Array in Java?

To find a peak element in an array, you can use various approaches. A peak element is an element that is greater than or equal to its neighbors. Here’s a simple algorithm in Java to find a peak element in an array:

public class PeakElementFinder {
// Function to find a peak element in an array
public static int findPeakElement(int[] arr) {
int n = arr.length;
// Check if the array is empty
if (n == 0) {
System.out.println("Array is empty");
return -1;
}
// Check the first and last elements separately
if (arr[0] >= arr[1]) {
return 0;
}
if (arr[n - 1] >= arr[n - 2]) {
return n - 1;
}
// Iterate through the array to find a peak element
for (int i = 1; i < n - 1; i++) {
if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) {
return i;
}
}
// If no peak element is found
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 20, 4, 1, 0};
int peakIndex = findPeakElement(arr);
if (peakIndex != -1) {
System.out.println("Peak element found at index: " + peakIndex);
System.out.println("Peak element value: " + arr[peakIndex]);
} else {
System.out.println("No peak element found in the array.");
}
}
}

This implementation checks the first and last elements separately and then iterates through the array to find a peak element. The time complexity of this solution is O(n). Note that this is a basic approach, and more efficient algorithms like binary search can be used for specific cases.