This is a Java Program to find peak element of an array. A peak element of an array is that element which is greater than its neighbors. The following program uses binary search approach to find a peak element. The time complexity of the following program is O (log n).
Here is the source code of the Java program to find peak element of an array using binary search. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/*
* Java Program to Find the peak element of an array using
* Binary Search approach
*/
import java.util.Scanner;
public class PeakElement2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of array");
int N = scan.nextInt();
int[] arr = new int[ N ];
/* Accept N elements */
System.out.println("Enter "+ N +" elements");
for (int i = 0; i < N; i++)
arr[i] = scan.nextInt();
/* Find Peak Elements */
System.out.print("\nPeak Elements : ");
peak(arr);
System.out.println();
}
public static void peak(int[] arr)
{
peak(arr, 0, arr.length - 1);
}
public static void peak (int arr[], int low, int high)
{
int N = arr.length;
if (high - low < 2)
return;
int mid = (low + high) / 2;
if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1])
System.out.print(arr[mid] +" ");
/* Recursively find other peak elements */
peak (arr, low, mid);
peak (arr, mid, high);
}
}
Enter size of array 8 Enter 8 elements 87 63 51 25 40 24 6 1 Peak Elements : 40
Related posts:
Remove All Occurrences of a Specific Value from a List
Spring Security Remember Me
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Period and Duration in Java
Sending Emails with Java
Java Program to Check Cycle in a Graph using Topological Sort
Spring Boot - Rest Template
Wilbur and Array
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Implement Shunting Yard Algorithm
Java Program to Implement Sorted Array
Converting Between a List and a Set in Java
Serve Static Resources with Spring
Java Program to Implement Ford–Fulkerson Algorithm
Prevent Cross-Site Scripting (XSS) in a Spring Application
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
@Order in Spring
SOAP Web service: Authentication trong JAX-WS
Custom JUnit 4 Test Runners
Show Hibernate/JPA SQL Statements from Spring Boot
Spring Boot - Google OAuth2 Sign-In
Java Program to Implement the Vigenere Cypher
Copy a List to Another List in Java
Java – Write a Reader to File
The “final” Keyword in Java
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Spring REST with a Zuul Proxy
Get and Post Lists of Objects with RestTemplate
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Spring Security Login Page with React
Convert a Map to an Array, List or Set in Java
Lấy ngày giờ hiện tại trong Java