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:
Kết hợp Java Reflection và Java Annotations
Introduction to Spring Cloud Netflix – Eureka
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Generating Random Numbers in a Range in Java
Java Program to Implement Best-First Search
Spring Boot - Introduction
Hướng dẫn Java Design Pattern – Prototype
Java Program to implement Dynamic Array
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Toán tử trong java
Comparing Dates in Java
HashSet trong java
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement Trie
Converting Between a List and a Set in Java
Java Program to Implement Adjacency List
Simplify the DAO with Spring and Java Generics
Wilbur and Array
Java Program to Find All Pairs Shortest Path
Lớp HashMap trong Java
Chuyển đổi từ HashMap sang ArrayList
Java equals() and hashCode() Contracts
Java Program to Implement Binary Search Tree
Java Program to Implement Graph Coloring Algorithm
A Guide to BitSet in Java
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Java Program to Perform Partial Key Search in a K-D Tree
Remove All Occurrences of a Specific Value from a List
The HttpMediaTypeNotAcceptableException in Spring MVC
Java Program to Find Inverse of a Matrix
A Guide to WatchService in Java NIO2
Generic Constructors in Java