import java.util.*; class labtask8 { static int a[],l,h,n,i,key; static void bsearch(int a[],int l,int h,int key) { int mid = (l+h)/2; while( l<=h ) { if (a[mid]<key ) { l=mid+1; } else if ( a[mid] == key ) { System.out.println("Element is found at location : " + (mid+1)); break; } else { h=mid-1; } mid=(l+h)/2; } if (l>h) { System.out.println("Element is not found"); } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter n"); n=sc.nextInt(); a=new int[n]; System.out.println("Enter "+n+" elements "); for(i=0;i<n;i++) { a[i]=sc.nextInt(); } System.out.println("Enter key"); key=sc.nextInt(); l=0; h=n-1; bsearch(a,l,h,key); }}
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