谁帮我用java写一个最简单的输入数字,然后进行二分查找法啊!!谢谢了!!
解决方案 »
- 求大神帮助!!!
- 我注释的地方什么作用啊 如果我想用产生的F调用内部类的方法 怎么做
- Random
- 关于随机数
- 自己写的一个JavaBean希望能够零修改复用到web,console,webservice3种应用上
- 下面这段程序为什么会有这样的错误提示,奇怪!!
- 关于TableModel 的 isCellEditable 方法
- 请问,在表示路径的时候"\"与"/"有何区别
- 请问,System.getProperties(),其中的key 可以自己在环境变量中设置么?急!
- java登录出错
- 几小时以后该去面试了。。。咋办。。。
- 我一直觉得这样写没有错。可是编译出错:int[] a = new int[2]{1,2}; 现在水平越来越差了。
int upperBound)
{
int curIn; curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn; // found it
else if(lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if(a[curIn] < searchKey) // it's in upper half
return recFind(searchKey, curIn+1, upperBound);
else // it's in lower half
return recFind(searchKey, lowerBound, curIn-1);
} // end else divide range
} // end recFind()
package fx.algorithm;/**
* 二分查找(针对一个有序数组) ,每次搜索取一半的范围
*
* @author 咖啡
*
*/
public class BinaryFind { private static int[] array = { 13, 27, 38, 49, 65, 76, 97, 88 }; public static void main(String[] args) {
System.out.println(search(38));
} private static int search(int searchKey) {
int lower = 0;
int upper = array.length - 1; while (true) {
int curIndex = (lower + upper) / 2; if (searchKey == array[curIndex])
return curIndex;
else if (lower > upper)
return -1;
else {
if (searchKey > array[curIndex])
lower = curIndex + 1;
else
upper = curIndex - 1;
}
} }
}
public static int[] Data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20 }; public static void main(String[] args) {
int weizhi = BinarySearch(8);
System.out.println(weizhi);
} public static int BinarySearch(int num) {
int L; // left
int R; // right
int M; // middle
int position = 0; L = 0;
R = Max - 1;
while (L <= R) {
M = (L + R) / 2;
if (num < Data[M])
R = M - 1;
else if (num > Data[M])
L = M + 1;
else if (num == Data[M]) {
position = M;
return position;
}
}
return position;
}}