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:
CharSequence vs. String in Java
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Introduction to Spring Security Expressions
Wrapper Classes in Java
Java Program to Perform the Unique Factorization of a Given Number
Java Program to Decode a Message Encoded Using Playfair Cipher
A Guide to JPA with Spring
Exploring the Spring Boot TestRestTemplate
Spring Boot - Apache Kafka
Send an email with an attachment
How to use the Spring FactoryBean?
Handling Errors in Spring WebFlux
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Guide to the Volatile Keyword in Java
Spring Cloud – Securing Services
Allow user:password in URL
Quick Guide to Spring Bean Scopes
Find the Registered Spring Security Filters
HandlerAdapters in Spring MVC
Introduction to Thread Pools in Java
Validate email address exists or not by Java Code
Hướng dẫn Java Design Pattern – Transfer Object
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
DistinctBy in the Java Stream API
Create a Custom Exception in Java
JUnit5 Programmatic Extension Registration with @RegisterExtension
Spring Boot - Hystrix
Java Program to Implement the Hill Cypher
Java Program to Generate Randomized Sequence of Given Range of Numbers
ExecutorService – Waiting for Threads to Finish
Java Program to Implement PrinterStateReasons API
Spring WebClient Filters