Using the Java Arrays Binary Search Methods

Arrays are a way to store a list of items that have the same primitive data type or class. Each item on the list goes into its own slot, which is numbered, so that the information can be easily accessed. Array can store any type of information that can be stored in a variable.

 

import java.util.*;

public class arraysearch

{

   public static void main(String aa[]) throws Exception

{

     int arrayelements[] = { 2, 5, -5, 6, -3, 8, 0, -8, -7, 4 };

     Arrays.sort(arrayelements);

     printArray("Sorted array Elements are", arrayelements);//function calling

     int index = Arrays.binarySearch(arrayelements,2);

     System.out.println( “Element is:”+index);  

}

   private static void printArray(String message, int arrayelements[]) //function

{

     System.out.println(message + ": [length: " + arrayelements.length + "]");

     for (int i = 0; i < arrayelements.length; i++) /*loop terminating when a condition(i<arrayelements.length)is no longer met*/

{

         if(i != 0)

{

           System.out.print(", ");

        }

         System.out.print(arrayelements[i]); //print all the elements

     }

     System.out.println(); //for space in all the elements

   }

}

 Arrays Binary Search Methods

Explanation….

In above example

sort ()(asc. to des.)(small to large)(negative to positive)is used to sort the elements in an Array

binarySearch () method is used to search the element(in this example 2 is the search index no.) . The user defined method printArray () is used to display the output.

     int index = Arrays.binarySearch(arrayelements,2);

By using binarySearch()we can search the elements in an array(2 is the index)

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @