Java Program to Find Maximum Element in an Array using Binary Search

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.

  1. //This is a java program to find maximum element using Binary Search
  2. import java.util.Random;
  3.  
  4. public class Maximum_Using_Binary 
  5. {
  6.     static int N = 20;
  7.     static int []sequence = new int[N];
  8.  
  9.     public static void sort()
  10.     {
  11.        int i, j, temp;
  12.         for (i = 1; i< N; i++) 
  13.         {
  14.             j = i;
  15.             temp = sequence[i];    
  16.             while (j > 0 && temp < sequence[j-1])
  17.             {
  18.                 sequence[j] = sequence[j-1];
  19.                 j = j-1;
  20.             }
  21.             sequence[j] = temp;            
  22.         }        
  23.     }
  24.  
  25.     public static void main(String args[])
  26.     {
  27.         Random random = new Random();
  28.  
  29.         for(int i=0; i<N; i++)
  30.             sequence[i] = Math.abs(random.nextInt(100));
  31.         System.out.println("The sequence is :");
  32.         for(int i=0; i<N; i++)
  33.             System.out.print(sequence[i] + " ");     
  34.  
  35.         sort();
  36.  
  37.         System.out.println("\nThe maximum element in the sequence is : " + sequence[N-1]);
  38.     }
  39. }

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

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.