Tuesday, 26 September 2017

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

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



  1. import java.util.Random;
  2.  
  3. public class Maximum_Using_Binary 
  4. {
  5.     static int N = 20;
  6.     static int []sequence = new int[N];
  7.  
  8.     public static void sort()
  9.     {
  10.        int i, j, temp;
  11.         for (i = 1; i< N; i++) 
  12.         {
  13.             j = i;
  14.             temp = sequence[i]; 
  15. //check next number is less than previous number, assume temp = 69, sequence[j-1] = 99
    //40 60 99(sequence[j-1]) 69(temp) 71 90 33 83 7 79 49 67 24 23 36 46 55 13 98 8  
  16.             while (j > 0 && temp < sequence[j-1]) 
  17.             {
  18.     //If it is less, then get previous number(99) to next number location(69)
  19.                 sequence[j] = sequence[j-1];  
  20.                 j = j-1;  //Point j to 60th location, bez to check in next loop 69 with 60
  21.             }
  22.             sequence[j] = temp;    //checking number finally add it to current location        
  23.         }        
  24.     }
  25.  
  26.     public static void main(String args[])
  27.     {
  28.         Random random = new Random();
  29.  
  30.         for(int i=0; i<N; i++)
  31.             sequence[i] = Math.abs(random.nextInt(100));
  32.         System.out.println("The sequence is :");
  33.         for(int i=0; i<N; i++)
  34.             System.out.print(sequence[i] + " ");     
  35.  
  36.         sort();
  37.  
  38.         System.out.println("\nThe maximum element in the sequence is : " + sequence[N-1]);
  39.     }
  40. }


Output:

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



No comments:

Post a Comment