First thing that we must keep in mind when applying binary search is that it works only on sorted lists. In this search technique, we begin our search from the middle element on the list.
If the key is found, we stop our search, otherwise, if the key is less than the middle element, the process is repeated in the left half of the list, otherwise, if the key is greater than the middle element, then the process is repeated in the right half of the list.
Below is the code written in Java that implements Binary Search in a one-dimensional array:
import java.io.*;
class BinarySearch{public static void main(String args[])throws IOException{InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader (isr);int a[]={7, 10, 12, 34, 45,51, 60, 78, 81, 92};int key, low=0, high=a.length-1, mid=0;System.out.print("Enter the integer to search:"); key=Integer.parseInt(br.readLine());while(low<=high){mid=(low+high)/2;
if (key==a[mid])
break;
else if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(low<=high)
System.out.println(key+" found at index "+mid);
else
System.out.println(key+" not found");
}
}