查找时的哨兵

今天偶然看到一个很巧的查找技巧,跟大家分享一下。

假设有一个数组a,要找到一个n使a[n]=key。

很简单吧,先看看一般的方法:

for(i = 1; i <= a.length; i++)
	if(a[i] == key)
		break;
// now a[i] = key, i > a.length means not found.

看看很巧的用哨兵的方法:

a[0] = key;
for(i = a.length; ; i--)
	if(a[i] == key)
		break;
// now a[i] = key, i = 0 means not found.

这样加上一个小小的哨兵(a[0])就节省了大约一半的时间!其实挺实用的。

3 thoughts on “查找时的哨兵

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">