二分查找-递归和非递归
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))
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))
相关文章推荐
- nginx 学习
- C++ o matching function for call to 'transform...错误
- mdadm使用详解及RAID 5简单分析
- mysql 性能优化方向
- 通过URL获取数据
- 前端性能优化(三)
- UIScrollView学习<1>理解 contentSize、contentInset和contentOffset
- leetcode刷题, 总结,记录, 备忘 230
- Android 短信验证
- 错误代码: 1109 Unknown table 'ename' in MULTI DELETE
- 华为OJ题库-字符串通配符
- 成功的背后!(给所有IT人)----转载:来自CSDN第一名博主
- 成功的背后!(给所有IT人)----转载:来自CSDN第一名博主
- 信汇中正领导力打造“必读12篇”之路
- linux rc.local 开机自启 rc.local中的命令不能自动运行
- 你是否真的需要说声“谢谢”?
- Unity NGUI中动态添加和删除sprite
- [Android] ImageView.ScaleType设置
- ASP.NET MVC 入门介绍 (上)
- iOS疯狂讲解之SQLite语句