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
advertisement

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.