1、非遞歸實現
int search(int a[], int n, int key)
{
int h = 0;
int t = n-1;
int m;
while(h < t)
{
int m = (h + t)>>1;
if(a[m] == key)
{
return m;
}
else if(a[m] > key)
{
t = m-1;
}
else
{
h = m+1;
}
}
return -1;
}
2、遞歸實現
int search(int a[], int h, int t, int key)
{
if(h < t)
{
int m = (h + t)/2;
if(a[m] == key)
return m;
else if(a[m] > key)
{
return (search(a, h, m-1, key));
}
else
{
return (search(a, m+1, t,key));
}
}
return -1;
}
二分查找又稱折半查找,優點是比較次數少,查找速度快,平均性能好;其缺點是要求待查表爲有序表,且插入刪除困難。因此,折半查找方法適用於不經常變動而查找頻繁的有序列表。假設其數組長度爲n,其算法複雜度爲o(log(n))