class binarySearch{
public static void main(String[] arg)
{
int n=10;
int arr[]={1,2,3,4,5,6,7,8,9,10};
int key=5;
int start=0;
int end=n-1;
while(start<end)
{
int mid=(start*end)/2;
if(arr[mid]==key)
{
System.out.println("key index is " + mid);
break;
}
else if(arr[mid]>key)
{
end=mid-1;
}
else if(arr[mid]<key)
{
start=mid+1;
}
if(start>end){
System.out.println("-1");
}
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter