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 Boot - Build Systems
Explain about URL and HTTPS protocol
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Tạo số và chuỗi ngẫu nhiên trong Java
Different Ways to Capture Java Heap Dumps
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Implement Sorted Array
Java – Random Long, Float, Integer and Double
Spring Boot - CORS Support
Spring REST API with Protocol Buffers
Spring Cloud – Bootstrapping
Converting String to Stream of chars
Java Program to implement Associate Array
Wrapper Classes in Java
Java Program to Generate Random Numbers Using Multiply with Carry Method
Java Program to Implement Bubble Sort
Transactions with Spring and JPA
Mapping a Dynamic JSON Object with Jackson
Java 8 and Infinite Streams
Giới thiệu java.io.tmpdir
A Guide to Queries in Spring Data MongoDB
Spring Boot Actuator
Class Loaders in Java
Java – Reader to InputStream
Convert XML to JSON Using Jackson
Creating a Generic Array in Java
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Lập trình đa luồng trong Java (Java Multi-threading)
Introduction to Java Serialization
Encode/Decode to/from Base64