二分查找
2012-12-01 23:18
204 查看
// //// 二分查找 #include <iostream> #include <assert.h> #include <algorithm> #include <stack> #include <vector> using namespace std; int biS(int *an, int s, int n) { int i=0, j=n-1,pos; if ( (s-an[i])*(s-an[j])>0) { return 0; } while (i<=j) { pos=i+((j-i)>>1); if(an[pos]<s) { i=pos+1; }else if (an[pos]>s) { j=pos-1; }else { return pos; } } return 0; } int main() { int an[100]; int i; for (i=0; i<100; i++) { an[i]=i*2; } sort(an,an+100); int n; for (i=0;i<100; i++) { int v=biS(an, i*2,100); cout<<"index: "<<v<<" value: "<<an[v]<<endl; } return 0; }
1.注意i+(j-i)/2比(i+j)/2好,注意>>比/好,注意>>的优先级,必须用括号把整个>>括起来
2.注意pos=i+1,必须是i+1,否则当j-i=1是会陷入死循环。
相关文章推荐
- 【jzoj3887】【字符串查询 】【二分查找】【可持久化trie】
- 华为中级机试题--二分查找树的应用
- 【数据结构】选择排序和二分查找
- POJ 2366 Sacrament of the sum(二分查找)
- 二分查找
- 二分查找
- 二分查找--AVL查找树
- POJ 1064 Cable master 二分查找
- 二分查找总结
- hdu 2578 Dating with girls(1)(二分查找)
- 二分查找iOS
- 二分查找
- 写好一段正确并且完整的二分查找也不容易
- 用Python实现二分查找
- Codeforces Round #417 (Div. 2) C. Sagheer and Nubian Market(二分查找)
- NYOJ 776 删除元素(二分查找)
- hiho一下 第三十七周 题目1 : 二分·二分查找之k小数
- 编程珠玑中关于二分查找的使用
- 二分查找递归和非递归
- 二分查找示例