class binarySearch{
public static void main(String[] arg)
{
int n=10;
int arr[]={10,9,8,7,6,5,4,3,2,1};
int key=10;
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