Binary search or half-interval search algorithm is used to find the position of the specific elements in a given data structure. Binary search follow divide and conquer strategy. In this problem we asked user to input the array size and after creating array again asked user to enter a value to search in array.
Source Code
import java.io.*; class Operate { int ret=-1; int bsearch(int a[],int first,int last,int key) { int mid; mid=(first+last)/2; if(first<=last) { if(a[mid]==key) ret=mid; else if(a[mid]>key) bsearch(a,first,mid-1,key); else bsearch(a,mid+1,last,key); } return ret; } } public class Binary { public static void main(String args[]) throws IOException { Operate op=new Operate(); InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); int n,i,k,key; int a[]=new int[50]; System.out.println("\n Enter n value:"); n=Integer.parseInt(br.readLine()); System.out.println(" \n Enter elements into array:"); for(i=0;i<n;i++) a[i]=Integer.parseInt(br.readLine()); System.out.println(" \n Enter key to search:"); key=Integer.parseInt(br.readLine()); k=op.bsearch(a,0,n-1,key); if(k!=-1) System.out.println("\nThe element "+key+" present at "+k); else System.out.println("\nElement not found in the array"); } }
Output of the Program
Binary search in Java |
0 comments:
Post a Comment