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:
Java – Write a Reader to File
Spring Boot - Runners
Java Program to Implement Shunting Yard Algorithm
Java Program to Implement LinkedBlockingQueue API
Request Method Not Supported (405) in Spring
Java Program to Generate a Random Subset by Coin Flipping
New Features in Java 10
Integer Constant Pool trong Java
Ways to Iterate Over a List in Java
The “final” Keyword in Java
Vòng lặp for, while, do-while trong Java
Java Program to Implement EnumMap API
Finding Max/Min of a List or Collection
Abstract class và Interface trong Java
Java Program to Generate Random Numbers Using Probability Distribution Function
Using a Spring Cloud App Starter
Java Program to Implement Skip List
Java Program to Check whether Undirected Graph is Connected using BFS
Hướng dẫn Java Design Pattern – Flyweight
Java Program to Find the GCD and LCM of two Numbers
Mảng (Array) trong Java
XML Serialization and Deserialization with Jackson
Hướng dẫn sử dụng Java Annotation
Java Program to implement Circular Buffer
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Java Program to Implement Vector API
Jackson – Change Name of Field
How to use the Spring FactoryBean?
Java Program to Implement Park-Miller Random Number Generation Algorithm
Java Program to Implement Find all Cross Edges in a Graph
Spring Boot: Customize the Jackson ObjectMapper
Java 8 StringJoiner