Binary Search:二分查找法
二分查找法,我理解的难点在于在什么情况下返回,也就是在什么条件下会RETURN。总结一下有以下这几种情况:
1,在查到的情况。这不用说了,找到要找的东东,当然要返回了。还要跑新任务呢,嘻嘻。
2,在下限值大于上限值时,返回查找失败(我感觉这儿是一个小难点)。为什么呢,首先,要搞明天,二分法在什么都查不到的情况下,只会有两种可能,A:在最少的一边;B:在最大的一边。这个可以用包含三个Element的Array来测试一下(当然是有顺的,这里我用的是从小到大的)。针对A这种情况,当Mid,low,supper都指向low时,下一步执行会supper = mid-1;此时low,supper,mid的关系是这样的:mid==low==supper+1;也就是说supper比low小一。这样看来,是无论如何也查不到了。针对B,也同样,low=mid+1;出现三者的关系是:mid==supper==low-1;supper又比low小了。也同样查不到了。
在《Data Structures and Algorithms In Java》这本书时在,作者是这样写的:
Binary Search with the find() Method
The find() method searches for a specified item by repeatedly dividing in half the
range of array elements to be considered. Here's how this method looks:
public int find(double searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn; // found it
else if(lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if(a[curIn] < searchKey)
lowerBound = curIn + 1; // it's in upper half
else
upperBound = curIn - 1; // it's in lower half
} // end else divide range
} // end while
} // end find()
The method begins by setting the lowerBound and upperBound variables to the first
and last occupied cells in the array. This specifies the range where the item we're looking
for, searchKey, may be found. Then, within the while loop, the current index, curIn,is set to the middle of this range.
If we're lucky, curIn may already be pointing to the desired item, so we first check if this
is true. If it is, we've found the item so we return with its index, curIn.
Each time through the loop we divide the range in half. Eventually it will get so small it
can't be divided any more. We check for this in the next statement: If lowerBound is
greater than upperBound, the range has ceased to exist. (When lowerBound equals
upperBound the range is one and we need one more pass through the loop.) We can't
continue the search without a valid range, but we haven't found the desired item, so we
return nElems, the total number of items. This isn't a valid index, because the last filled
cell in the array is nElems-1. The class user interprets this value to mean that the item
wasn't found.
If curIn is not pointing at the desired item, and the range is still big enough, then we're
ready to divide the range in half. We compare the value at the current index, a[curIn],
which is in the middle of the range, with the value to be found, searchKey.
If searchKey is larger, then we know we should look in the upper half of the range.
Accordingly, we move lowerBound up to curIn.
Actually we move it one cell beyond curIn, because we've already checked curIn itself
at the beginning of the loop.
If searchKey is smaller than a[curIn], we know we should look in the lower half of the
range. So we move upperBound down to one cell below curIn.
写到这儿吧。嘿嘿!!!