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:
Spring Data MongoDB Transactions
Get and Post Lists of Objects with RestTemplate
How to Read HTTP Headers in Spring REST Controllers
Send email with JavaMail
Difference Between Wait and Sleep in Java
Luồng Daemon (Daemon Thread) trong Java
Java Program to Implement Shunting Yard Algorithm
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java Program to Implement Efficient O(log n) Fibonacci generator
Java equals() and hashCode() Contracts
Spring Boot - Service Components
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Represent Linear Equations in Matrix Form
Vector trong Java
Java Program to Implement Strassen Algorithm
Java Program to Implement Insertion Sort
Java 8 StringJoiner
Deque và ArrayDeque trong Java
ETL with Spring Cloud Data Flow
Giới thiệu JDBC Connection Pool
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Generating Random Dates in Java
Adding a Newline Character to a String in Java
Java 8 – Powerful Comparison with Lambdas
Consuming RESTful Web Services
Java Program to Implement Control Table
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Java Program to Decode a Message Encoded Using Playfair Cipher
Quick Guide to java.lang.System
Getting Started with Stream Processing with Spring Cloud Data Flow
Serve Static Resources with Spring
Ép kiểu trong Java (Type casting)