int BinarySearch(staticTable *Tbl; ElementType K)
{
int left,right,mid,NoFound=-1;
left=1;
right=Tbl->Length;
while (left<=right)
{
mid=(left+right)/2;
if(K<Tbl->Element[mid]) right=mid-1;/* **可以变成right=mid;***/
else if(K>Tbl->Element[mid]) left=mid+1;/* **可以变成left=mid;***/
else return mid;
}
return NotFound;
}
可能会死循环,比如进入循环体的时候left
为1,right
为2,并且K
>Tbl->Element[1]
…
一种是:
int BinSearch(int target, int nums[]){
int low = 0, high = nums.length - 1;
while(low <= high){
int mid = (low + high) / 2;
if(nums[mid] == target)
return mid;
if(nums[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
另一种:
int BinSearch(int target, int nums[]){
int low = 0, high = nums.length;
while(low < high){
int mid = (low + high) / 2;
if(nums[mid] == target)
return mid;
if(nums[mid] < target)
low = mid + 1;
else
high = mid;
}
return -1;
}