This is a java program to find the maximum element using binary search technique. Binary search requires sequence to be sorted. We return the last element of the sequence, which is maximum.
Here is the source code of the Java Program to Find Maximum Element in an Array using Binary Search. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a java program to find maximum element using Binary Search
import java.util.Random;
public class Maximum_Using_Binary
{
static int N = 20;
static int []sequence = new int[N];
public static void sort()
{
int i, j, temp;
for (i = 1; i< N; i++)
{
j = i;
temp = sequence[i];
while (j > 0 && temp < sequence[j-1])
{
sequence[j] = sequence[j-1];
j = j-1;
}
sequence[j] = temp;
}
}
public static void main(String args[])
{
Random random = new Random();
for(int i=0; i<N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("The sequence is :");
for(int i=0; i<N; i++)
System.out.print(sequence[i] + " ");
sort();
System.out.println("\nThe maximum element in the sequence is : " + sequence[N-1]);
}
}
Output:
$ javac Maximum_Using_Binary.java $ java Maximum_Using_Binary The sequence is : 40 60 99 69 71 90 33 83 7 79 49 67 24 23 36 46 55 13 98 8 The miaximum element in the sequence is : 99
Related posts:
Intro to Spring Boot Starters
Sử dụng CountDownLatch trong Java
Java Program to Represent Linear Equations in Matrix Form
Java Program to Represent Graph Using Linked List
Spring Data Java 8 Support
Java Program to Implement PriorityBlockingQueue API
Performance Difference Between save() and saveAll() in Spring Data
Java Program to Implement the Program Used in grep/egrep/fgrep
A Guide to @RepeatedTest in Junit 5
Ép kiểu trong Java (Type casting)
Introduction to the Java ArrayDeque
Spring Security and OpenID Connect
StringBuilder vs StringBuffer in Java
Apache Tiles Integration with Spring MVC
Simple Single Sign-On with Spring Security OAuth2
Hướng dẫn Java Design Pattern – State
Lớp Properties trong java
Call Methods at Runtime Using Java Reflection
Hướng dẫn Java Design Pattern – Iterator
Java Program to Find Transitive Closure of a Graph
How to Read a Large File Efficiently with Java
Java Program to Represent Graph Using Incidence List
Java 14 Record Keyword
Implementing a Binary Tree in Java
Hướng dẫn Java Design Pattern – Null Object
Java Program to Implement Hash Tables
A Guide to Apache Commons Collections CollectionUtils
OAuth 2.0 Resource Server With Spring Security 5
Filtering and Transforming Collections in Guava
Java Program to Check whether Graph is a Bipartite using BFS
Java IO vs NIO
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph