Showing posts with label Binary Search algorithm implmentation. Show all posts
Showing posts with label Binary Search algorithm implmentation. Show all posts

Saturday, August 18, 2012

How to find element using binary search algorithm


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;

}
}