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

Java examples for java.util:Arrays

Description

Binary search int Array for the value 5

Demo Code

import java.util.Arrays;

public class Main 
{
   public static void main(String[] args)
   {/*from   www .  j av a  2 s  . c  om*/
     // copy array intArray into array intArrayCopy
     int[] intArray = {1, 2, 3, 4, 5, 6};
     displayArray(intArray, "intArray");
     
     // search intArray for the value 5
     int location = Arrays.binarySearch(intArray, 5); 
     
     if (location >= 0)
        System.out.printf(
           "Found 5 at element %d in intArray%n", location); 
     else
        System.out.println("5 not found in intArray"); 
   } 

   // output values in each array
   public static void displayArray(int[] array, String description)
   {     
      System.out.printf("%n%s: ", description);

      for (int value : array)
         System.out.printf("%d ", value);
   } 
}

Result


Related Tutorials