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:
Guide to Spring @Autowired
Introduction to Spring Cloud Stream
Spring Boot - Admin Client
How to Get the Last Element of a Stream in Java?
Java Program for Topological Sorting in Graphs
Apache Tiles Integration with Spring MVC
How to Get All Dates Between Two Dates?
Luồng Daemon (Daemon Thread) trong Java
Get the workstation name or IP
Concurrent Test Execution in Spring 5
Java Program to Implement RenderingHints API
An Intro to Spring Cloud Security
Biểu thức Lambda trong Java 8 – Lambda Expressions
Quick Guide to Spring MVC with Velocity
Quick Intro to Spring Cloud Configuration
Java Program to Perform Insertion in a BST
A Guide To UDP In Java
Java Program to Implement Self Balancing Binary Search Tree
Java Program to Implement Stein GCD Algorithm
Java Program to Generate Random Numbers Using Middle Square Method
Integer Constant Pool trong Java
Chuyển đổi giữa các kiểu dữ liệu trong Java
The Spring @Controller and @RestController Annotations
Java Program to Find the GCD and LCM of two Numbers
Prevent Cross-Site Scripting (XSS) in a Spring Application
Collect a Java Stream to an Immutable Collection
Enum trong java
Introduction to Using FreeMarker in Spring MVC
Java Program to Find the Edge Connectivity of a Graph
Java Program to Implement Bellman-Ford Algorithm
Summing Numbers with Java Streams
Tìm hiểu về Web Service