【发布时间】:2015-03-21 20:36:51
【问题描述】:
我知道这是一个非常有名的问题,并且已经提供了很多答案,但我正在尝试在我自己的 java 中实现二进制搜索算法。
首先得到以下编译错误,为什么?
这个方法必须返回一个int类型的结果
第二种方法与this famous solution的不同之处
public static int binarySearch(int test[], int num){
int midLength = test.length/2;
int fullLength = test.length;
if(num > test[midLength]){
int newArray[] = new int[fullLength - midLength];
for (int j = 0; j<= midLength ; j++){
newArray[j] = test[midLength + j];
}
return binarySearch(newArray, num);
}
else if(num < test[midLength]){
int newArray[] = new int[midLength];
for (int j = 0; j<= fullLength - midLength ; j++){
newArray[j] = test[j];
}
return binarySearch(newArray, num);
}
else if(num == test[midLength]){
return test[midLength];
}
}
public static void main(String[] args) {
int test[] = {2,8,1,6,4,6};
Arrays.sort(test);
int num = ArraysTest.binarySearch(test, 1);
System.out.println(num);
}
请忽略边界条件和逻辑错误,因为这是草稿版本。
【问题讨论】:
标签: java arrays algorithm binary-search