import java.util.Arrays;
public class BinarySearchAlgo {
public static void main(String args[]){
int a[]={1,4,52,5,2,6,9,12};
int sval=4;
Arrays.sort(a);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println("\n Element location");
System.out.print(binarySearch(a,sval));
}
private static int binarySearch(int[] a, int sval) {
int left=0;
int right=a.length-1;
return bsearch(a,sval,left,right);
}
private static int bsearch(int[] a, int sval, int left, int right) {
if(right<left)
return -1;
int mid=(left+right)/2;
if(sval<a[mid])
return bsearch(a,sval,left,mid-1);
else if(sval>a[mid])
return bsearch(a,sval,mid+1,right);
else
return mid;
}
}
No comments:
Post a Comment
Thanks for your valuable comments