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 Program to Implement Hash Tree
Converting Strings to Enums in Java
Apache Commons Collections Bag
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Java – Delete a File
Collect a Java Stream to an Immutable Collection
Converting Between an Array and a Set in Java
Java Program to Implement Unrolled Linked List
Spring Security 5 – OAuth2 Login
Custom Exception trong Java
The Guide to RestTemplate
Composition, Aggregation, and Association in Java
Java Program to Implement LinkedTransferQueue API
Apache Commons Collections OrderedMap
Bootstrapping Hibernate 5 with Spring
Java equals() and hashCode() Contracts
Lớp lồng nhau trong java (Java inner class)
HttpClient Connection Management
Java Program to Check if a Matrix is Invertible
An Introduction to ThreadLocal in Java
Java Program to Implement Rolling Hash
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Spring Boot - Enabling Swagger2
Sắp xếp trong Java 8
Java Program to Perform Deletion in a BST
Java Program to Implement Variable length array
Java Program to Implement Hash Trie
Java Program to Implement Bubble Sort
Apache Commons Collections SetUtils
Lớp Arrarys trong Java (Arrays Utility Class)
Guide to Dynamic Tests in Junit 5
Lập trình đa luồng với Callable và Future trong Java