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:
Java Program to Implement Hash Tables Chaining with List Heads
Spring Boot - Introduction
Java Program to Implement Double Order Traversal of a Binary Tree
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Java Program to implement Sparse Vector
Configure a RestTemplate with RestTemplateBuilder
Pagination and Sorting using Spring Data JPA
File Upload with Spring MVC
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Find a Good Feedback Edge Set in a Graph
Hướng dẫn Java Design Pattern – Decorator
Zipping Collections in Java
Spring Boot Gradle Plugin
Comparing Objects in Java
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Iterable to Stream in Java
Period and Duration in Java
Java Program to Implement Word Wrap Problem
So sánh HashMap và HashSet trong Java
Guide to the Synchronized Keyword in Java
Java Program to Implement Stack API
Ép kiểu trong Java (Type casting)
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
String Operations with Java Streams
Merging Streams in Java
Limiting Query Results with JPA and Spring Data JPA
The Registration API becomes RESTful
Logging in Spring Boot
Converting between an Array and a List in Java
Checking for Empty or Blank Strings in Java
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Tìm hiểu về Web Service