import java.util.Arrays;
Demonstration of the classic Binary Search
@author
@version
public class BinarySearch{
Binary search - recursively looks for an item in a sorted array by
reducing the search space to half the previous search space.
@param a
@param item
@return
public static boolean binarySearch( int[] a, int item ){
return binarySearchRec( a, item, 0, a.length - 1);
}
Binary search - recursively looks for an item in a sorted array by
reducing the search space to half the previous search space.
@param a
@param item
@param startIndex
@param endIndex
@return
private static boolean binarySearchRec( int[] a, int item, int startIndex, int endIndex ){
if( startIndex > endIndex ){
return false;
}
int midIndex = (startIndex + endIndex) / 2;
int midValue = a[ midIndex ];
if( item > midValue ){
return binarySearchRec( a, item, midIndex + 1, endIndex);
}else if( item < midValue ){
return binarySearchRec( a, item, startIndex, midIndex - 1);
}else{
return true;
}
}
public static void main( String[] args ){
int[] array1 = {0,1,2,3,4,6,8,9};
int[] array2 = {0,0,1,2,3,3,4,6,8,9};
int search = 3;
int[] array = array1;
boolean result = false;
array = array1;
search = 3;
result = binarySearch( array, search );
System.out.println( "binarySearch( array="+Arrays.toString(array)+", search="+search+" ) returns "+result);
array = array1;
search = 7;
result = binarySearch( array, search );
System.out.println( "binarySearch( array="+Arrays.toString(array)+", search="+search+" ) returns "+result);
array = array2;
search = 3;
result = binarySearch( array, search );
System.out.println( "binarySearch( array="+Arrays.toString(array)+", search="+search+" ) returns "+result);
}
}