Of course, the premise is: Ordered series, here in ascending order for example!
Public classBinarySearch { Public Static voidMain (string[] args) {intarr[]={1,2,3,4,5,6,7,8,9}; intKey=9; //int Result=binarysearchmethod_nodigui (arr,key);//non-recursive implementation intResult=binarysearchmethod_digui (Arr,0,arr.length-1,key);//Recursive ImplementationSYSTEM.OUT.PRINTLN ("Result:" +result); } Public Static intBinarysearchmethod_nodigui (intArr[],intkey) { intLeft =0; intRight=arr.length-1; intMid= (left+right) >>1; while(left<=Right ) { if(arr[mid]==key) { returnmid; }Else if(arr[mid]>key) { Right=mid-1; }Else{ Left=mid+1; } Mid= (left+right) >>1; } return-1; } Public Static intBinarysearchmethod_digui (intArr[],intLeftintRightintkey) { intMid= (left+right) >>1; if(left>Right ) { return-1; } if(arr[mid]==key) { returnmid; }Else if(arr[mid]>key) { Right=mid-1; returnBinarysearchmethod_digui (Arr,left,right,key); }Else{ Left=mid+1; returnBinarysearchmethod_digui (Arr,left,right,key); } }}
Binary lookup (recursive and non-recursive implementations)