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:
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Implement Cartesian Tree
Setting Up Swagger 2 with a Spring REST API
Spring @RequestParam Annotation
Java Program to Implement Bellman-Ford Algorithm
Remove the First Element from a List
Join and Split Arrays and Collections in Java
Sending Emails with Java
Multi Dimensional ArrayList in Java
Guide to Character Encoding
Spring Boot - Bootstrapping
Java Program to Implement the Checksum Method for Small String Messages and Detect
Java 8 Collectors toMap
JUnit5 @RunWith
Java Program to Implement String Matching Using Vectors
Exploring the Spring Boot TestRestTemplate
Spring Boot - Apache Kafka
Quick Guide to Spring Controllers
How to Read HTTP Headers in Spring REST Controllers
Calling Stored Procedures from Spring Data JPA Repositories
Explain about URL and HTTPS protocol
Java Program to implement Associate Array
Java Program to Implement VList
Cài đặt và sử dụng Swagger UI
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Các kiểu dữ liệu trong java
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Đồng bộ hóa các luồng trong Java
Java – Rename or Move a File
Guide to Spring 5 WebFlux
Java Program to Represent Graph Using Adjacency Matrix