我一直在思考如何优化我的二进制搜索。代码如下。到目前为止,我所做的是:
我所能想到的就是处理不同的输入。
当搜索元素超出范围时优化最坏情况(最坏情况之一),即搜索低于最低值或高于最高值的数字。当可以保证不会在输入中找到O(logn)比较时,这样可以节省比较。
int input[15] = {1,2,2,3,4,5,5,5,5,6,7,8,8,9,10};
/*
* Returns index p if a[p] = value else -ve int.
* value is value being searched in input.
*/
int
binary_search (int * input, int low, int high, int value)
{
int mid = 0;
if (!input) return -1;
if (low > high) return -1;
/* optimize worst case: value not in input */
if ((value < input[low]) || (value > input[high]))
{ return -2; }
mid = (low + high)/2;
if (input[mid] == value) {
return mid;
}
if (input[mid] > value) {
return binary_search(input, low, mid -1, value);
} else {
return binary_search(input, mid+1, high, value);
}
}
我能想到的另一个最坏的情况是,要搜索的值是在输入的中间位置还是在第一个元素的旁边。我认为更笼统的是对binary_search的每次调用的输入下限/上限。这也需要算法进行准确的登录比较。
关于我可以重点改进的其他方面的任何其他建议。我不需要代码,但指导会有所帮助。谢谢。
乔恩·本特利(Jon Bentley)的《编程珍珠》(Programming Pearls)在优化二进制搜索方面有一章不错。请参阅http://www.it.iitb.ac.in/~deepak/deepak/placement/Programming_pearls.pdf中的第4章
其中一种变体具有惊人的效率(请参阅“代码调整”一章中的第87页):
# Search a 1000-element array
l = 0
if x[512] < t: l = 1000 + 1 - 512
if x[l+256] < t: l += 256
if x[l+128] < t: l += 128
if x[l+64] < t: l += 64
if x[l+32] < t: l += 32
if x[l+16] < t: l += 16
if x[l+8] < t: l += 8
if x[l+4] < t: l += 4
if x[l+2] < t: l += 2
if x[l+1] < t: l += 1
p = l + 1
if p > 1000 or x[p] != t:
p = 0 # Not Found
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句