您的位置:首页 > 其它

二分查找-递归和非递归

2015-09-16 19:21 274 查看
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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: