ADS

Binary Search For Integer In Array

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 elements
8
Enter elements into array
6
9
8
7
5
6
45
45
Enter search element
8
Sorted array
--------------
5
6
6
7
8
9
45
45
Element 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.

Subscribe to receive free email updates:

ADS