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:
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java Program to Find Nearest Neighbor for Static Data Set
Encode/Decode to/from Base64
Java Copy Constructor
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Receive email by java client
Giới thiệu về Stream API trong Java 8
Model, ModelMap, and ModelAndView in Spring MVC
Guide to CountDownLatch in Java
Converting String to Stream of chars
Iterating over Enum Values in Java
Spring Boot - CORS Support
Converting Strings to Enums in Java
Allow user:password in URL
Map Interface trong java
Java Program to Find Transitive Closure of a Graph
Java Program to Implement Sieve Of Eratosthenes
Spring Boot - Code Structure
Difference Between Wait and Sleep in Java
Spring Data JPA @Modifying Annotation
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Hướng dẫn Java Design Pattern – Composite
Lớp Properties trong java
Spring Boot - Thymeleaf
Java Program to Implement Lloyd’s Algorithm
Java Program to Find the Edge Connectivity of a Graph
Lớp HashMap trong Java
Java Program to Implement Sorted Circular Doubly Linked List
Add Multiple Items to an Java ArrayList
Giới thiệu Google Guice – Binding
What is Thread-Safety and How to Achieve it?
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull