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:
Giới thiệu Aspect Oriented Programming (AOP)
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Java Program to Solve a Matching Problem for a Given Specific Case
ClassNotFoundException vs NoClassDefFoundError
An Intro to Spring Cloud Contract
More Jackson Annotations
Stack Memory and Heap Space in Java
A Quick Guide to Using Keycloak with Spring Boot
Implementing a Runnable vs Extending a Thread
Generating Random Numbers in a Range in Java
Spring Boot Actuator
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
A Guide to the Java LinkedList
Java Program to Implement Horner Algorithm
Java Program to Implement Fenwick Tree
Logout in an OAuth Secured Application
Hướng dẫn sử dụng Lớp FilePermission trong java
LIKE Queries in Spring JPA Repositories
Check if a String is a Palindrome in Java
Wilbur and Array
The Registration Process With Spring Security
Hướng dẫn Java Design Pattern – Mediator
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Java Program to Generate N Number of Passwords of Length M Each
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
ExecutorService – Waiting for Threads to Finish
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Implement AA Tree
How to Read a Large File Efficiently with Java
Java Program to Implement Segment Tree
Tránh lỗi NullPointerException trong Java như thế nào?
Introduction to Java Serialization