/**
* 二分查找法
* 对有序序列中的元素进行查找
* 从序列中间开始查找
* 如果该值大于期望值,缩小查找区间至左边
* 如果该值小于期望值,缩小查找区间至右边
*/
package al;
public class BinSearch {
public static void main(String[] args) {
int[] number = {1, 2, 6, 9, 22, 44, 95, 121, 346};
BinSearch bin = new BinSearch();
int result = bin.Search(number, 346);
System.out.println("Result position is "+result);
}
/**
* @author
* @param number 有序序列
* @param dest 期望值
* @return 该值在序列中的位置
*/
public int Search(int[] number, int dest) {
int low = 0;
int high = number.length -1;
int mid;
while(low <= high) {
mid = (low+high)/2;
if (number[mid] > dest) {
high = mid -1;
}else if (number[mid] < dest) {
low = mid+1;
} else
return mid;
}
return -1;
}
}
Java实例14 - 二分查找
最新推荐文章于 2022-04-15 11:14:55 发布