The following example illustrates binary search of int in array.
import java.util.*;
class SearchInt
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no.of elements");
int n=s.nextInt();
System.out.println("Enter elements into array");
int[] a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
System.out.println("Enter search element");
int sr=s.nextInt();
Arrays.sort(a);
System.out.println("Sorted array\n--------------");
for(int k:a)
System.out.println(k);
int idx=Arrays.binarySearch(a,sr);
System.out.println("Element found at (after sorting) "+idx);
}
}
Sample Output
Enter no.of elements8Enter elements into array6987564545Enter search element8Sorted array--------------5667894545Element found at (after sorting) 4
binarySearch(a,sr): Takes array and search element respectively. Static method of the class.
sort(a): a must be sorted before searching for proper results. Static method.
idx: The index (may be any index if repeated more than 1 time). index value is with respect to the sorted array and not to the original one.
Arrays: Located in the java.util package.