日期:2014-05-20 浏览次数:20967 次
public class arrayBinary{
/**
* @param 要查找的数组和要查找的值,前提是数组要从小到大排列好
*/
public static int bsearch(int array[],int value){
boolean found = false; // 是否找到
int high = array.length - 1; // 二分法中的要查找的高位
int low = 0; // 二分法中的要查找的低位
int cnt = 0; //查找步数
int mid = (high + low)/2; // 二分法要点,二分啊
System.out.println("Looking for "+value);
while(!found && (high >= low)){ // 边界条件
System.out.print(" Low " + low + " Mid " + mid);
System.out.print(" High " + high);
if(value == array[mid]) // 等于中间的值,找到了 ;)
found = true;
else // 没找到 ;(
if(value < array[mid]) // 若要找的数比中间的数小,当然到数组的前半部分找
high = mid - 1; // 将高位变成中间那个数的前一个数
else // 若要找的数比中间的数还大,当然到数组的后半部分找喽
low = mid + 1; // 将低位变成中间那个数还大一个数
mid = (high + low)/2; // 不管是前部分还是后部分,找到中间的那个位置先
cnt++; // 又查了一步了哦
}
System.out.println();
System.out.println("Steps " + cnt);
return((found) ? mid : -1); // 找到还是没找到啊,没找到,-1给你吧
}
public static void main(String[] args){
int array[]=new int[100];
for(int i=0;i < array.length;i++)
array[i]=i;
System.out.println("Resulte "+bsearch(array,67));
System.out.println("Resulte "+bsearch(array,33));
System.out.println("Resulte "+bsearch(array,1));
System.out.println("Resulte "+bsearch(array,1001));
}
}
------解决方案--------------------
顶
------解决方案--------------------
Arrays.binarySearch(int[]a, value)
java中已经有比较优化的方法实现了,直接调用即可
------解决方案--------------------
Arrays, Collections中分别有关于数组和Collection的查找方法供调用.