public class Test4 {
public int binarySearch(int[] items, int value){
int startIndex = 0;
int stopIndex = items.length - 1;
int middle = (int)Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area(调整查找范围)
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle(重新计算中项索引)
middle = (int)Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value(确保返回正确的值)
return (items[middle] != value) ? -1 : middle;
}
/**
* @param args
*/
public static void main(String[] args) {
Test4 t = new Test4();
int aa[]={1,3,5,7,9};
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!"+t.binarySearch(aa, 5));
}
}