April 14, 2011

Binary Search of an Integer Array

Binary Search Program. It's written in Java, but it's almost same as C program. All you need is just use 'sizeOf()' macro (fuction) to get the length of array.


public static void main(String[] args) {
int input[] = {1,3,5,6,7,8,9,10,11};
                int query = 3;
System.out.println(query + " is in input[" + binarySearch(input, query) + "].");
}

public static int binarySearch(int tree[], int query) {
int beg = 0;
int end = tree.length-1;
int mid = (beg+end)/2;

for(int i=1; mid >=0 ;i++) {
System.out.println(i+ "th try - index:" + (mid + 1) + "/" + tree.length);
if(tree[mid] == query)
break;
else if(tree[mid] > query)
end = mid - 1;
else
beg = mid +1;

mid = (beg + end)/2;
   if (beg >= med)
      mid = -1;
}
return mid;
}