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:
An Introduction to Java.util.Hashtable Class
A Guide to System.exit()
Guide to the Java ArrayList
Spring Boot - Servlet Filter
Tổng quan về ngôn ngữ lập trình java
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Java Program to Implement Dijkstra’s Algorithm using Set
Iterable to Stream in Java
Java Program to Generate Random Numbers Using Multiply with Carry Method
Handling Errors in Spring WebFlux
Functional Interfaces in Java 8
Java Program to Perform Naive String Matching
HttpClient Timeout
Java Program to Find Transpose of a Graph Matrix
How to Iterate Over a Stream With Indices
Object cloning trong java
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
An Intro to Spring Cloud Contract
Sử dụng CountDownLatch trong Java
New Features in Java 11
Java Program to Perform Uniform Binary Search
Receive email by java client
Java Program to Implement VList
JWT – Token-based Authentication trong Jersey 2.x
Spring Cloud Connectors and Heroku
Xử lý ngoại lệ trong Java (Exception Handling)
Java Program to Implement Max Heap
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Remove All Occurrences of a Specific Value from a List
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
A Guide to TreeSet in Java