优点:查找速度快;平均性能好;
缺点:必须是有序表
思路:假设表中元素按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功; 否则利用中间位置将表分成前后两部分,若中间位置的记录关键字大于查找关键字,则进一步查找前一字表、否则查找后一字表。。重复过程,直到成功或失败。
int BinSearch(int a[], int nBeginPos, int nEndPos, int nKey)
{
int nMid = 0;
while (nBeginPos <= nEndPos)
{
nMid = (nBeginPos+nEndPos)/2;
if (nKey < a[nMid])
{
nEndPos = nMid - 1;
}
else if (nKey > a[nMid])
{
nBeginPos = nMid + 1;
}
else
return nMid; //查到
}
return -1; //没查到
}
int main()
{
int a[] = {1,3,6,8,9,15};
int nResult = BinSearch(a, 0, sizeof(a)/sizeof(a[0]) - 1, 8); //sizeof(a)/sizeof(a[0]) - 1为数组末尾元素;8为Key值
if (-1 == nResult)
{
cout<<"Not find"<<endl;
}
else
cout<<"Find"<<endl;
system("pause");
return 0;
}