[英]How to use binary search of a sorted list and then count the comparisons
我试图使用我的排序列表,并通过二进制搜索实现它。 然后,我想计算找到关键字所需的比较次数。 我的代码是:
public class BinarySearch {
private static int comparisions = 0;
public static void main(String[] args) {
int [] list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int i = BinarySearch.BinSearch(list, 20);
System.out.println(comparisions);
}
public static int BinSearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
int mid = (high + low) / 2;
if (key < list[mid]) {
high = mid - 1;
comparisions++;
} else if (key == list[mid]) {
return mid;
comparisions++;
} else {
low = mid + 1;
comparisions++;
}
return -1;
}
}
到目前为止,无论键是多少,它只给我1作为比较。
您的代码缺少搜索的循环部分,可以使用递归或使用while
循环来完成循环。 在这两种情况下,您都必须问自己是否是否只想知道计数或实际返回比较计数。 由于您的方法现在返回索引,因此无法轻松同时返回比较计数。 为此,您需要返回两个整数的数组或自定义class IndexAndComparisonCount { ... }
。
如果您使用递归方法,则每次进行比较时都需要递增,并且在执行递归调用时,您需要获取该递归调用的返回值,并增加compareCount,将调用计数返回1:
if (... < ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 1;
return ret;
} else if (... > ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 2; // since you did compare twice already
return ret;
} else {
return new IndexAndComparisonCount(mid, 2); // you compared twice as well
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.