Binary search int Array for the non-existing value - Java java.util

Java examples for java.util:Arrays

Description

Binary search int Array for the non-existing value

Demo Code

import java.util.Arrays;

public class Main 
{
   public static void main(String[] args)
   {/*from ww  w  .j  a  va  2 s.  c  om*/
     // copy array intArray into array intArrayCopy
     int[] intArray = {1, 2, 3, 4, 5, 6};
     // search intArray for the value 5
     int location = Arrays.binarySearch(intArray, 5); 
     

     // search intArray for the value 8
     location = Arrays.binarySearch(intArray, 8);

     if (location >= 0)
        System.out.printf(
           "Found 8 at element %d in intArray%n", location); 
     else{
       System.out.println("8 not found in intArray");
       System.out.printf("%d in intArray%n", location);
       //Use abstract value for location to insert value
     }        
   } 
}

Result


Related Tutorials