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:
Connect through a Proxy
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Quick Guide to Spring MVC with Velocity
HttpClient 4 Cookbook
Spring Cloud AWS – S3
Java Program to Implement Direct Addressing Tables
Java Program to Implement Vector API
Convert XML to JSON Using Jackson
Java Program to Implement Warshall Algorithm
Java Program to implement Sparse Vector
Java Program to Implement Unrolled Linked List
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Automatic Property Expansion with Spring Boot
A Guide to Concurrent Queues in Java
Spring Cloud Bus
Apache Camel with Spring Boot
Guide to BufferedReader
Java Program to Find kth Largest Element in a Sequence
Spring Boot - CORS Support
Guide to java.util.concurrent.BlockingQueue
Introduction to Spring Cloud CLI
How to Convert List to Map in Java
Spring Boot - Rest Controller Unit Test
Introduction to Netflix Archaius with Spring Cloud
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement SimpeBindings API
Guide to the ConcurrentSkipListMap
Java Program to Perform Finite State Automaton based Search
Java Program to Search for an Element in a Binary Search Tree
Guide To CompletableFuture
Shuffling Collections In Java