我问,因为我基本上只是将我的python代码翻译成java,当我在python中测试结果是预期的(二进制搜索比顺序搜索更快)。但是在Java中并非如此。为什么我的二进制搜索效率低下?
import java.util.Arrays;
import java.util.stream.IntStream;
public class Chap5exe1 {
private static boolean sequential_search(int[] iterable, int item){
boolean found = false;
boolean stop = false;
int current_position = 0;
while ((current_position < iterable.length) & (!found) & (!stop)){ //!found is found == false
if (iterable[current_position] == item){
found = true;
}
else if (iterable[current_position] > item){
stop = true;
}
else {
current_position += 1;
}
}
return found;
}
private static boolean binary_search(int[] iterable, int item) {
if (iterable.length == 0) {
return false;
}
int mid_point = iterable.length / 2;
if (iterable[mid_point] == item){
return true;
}
else if (iterable[mid_point] > item){
return binary_search(Arrays.copyOfRange(iterable, 0, mid_point), item);
}
else {
return binary_search(Arrays.copyOfRange(iterable, mid_point+1, iterable.length), item);
}
}
public static void main(String[] args) {
for(int i = 1000; i <= 10000000; i += 1000){
int[] list = IntStream.range(0, i).toArray();
long startTime1 = System.nanoTime();
sequential_search(list, i);
long stopTime1 = System.nanoTime();
long startTime2 = System.nanoTime();
binary_search(list, i);
long stopTime2 = System.nanoTime();
String output = String.format("Sequential search:%d / Binary search:%d", stopTime1-startTime1, stopTime2-startTime2);
System.out.println(output);
}
}}
答案 0 :(得分:0)
如评论中所述,Arrays.copyOfRange()方法调用会导致开销。请尝试使用以下代码:
private static boolean binary_search(int[] iterable, int item) {
if (iterable.length == 0) {
return false;
}
return binary_search(iterable, item, 0, iterable.length);
}
private static boolean binary_search(int[] iterable, int item, int start, int end) {
int mid_point = (start + end) / 2;
if (iterable[mid_point] == item){
return true;
} else if (start == end) {
return false;
}
else if (iterable[mid_point] > item){
return binary_search(iterable, item, start, mid_point);
}
else {
return binary_search(iterable, item, mid_point+1, end);
}
}