二分查找

来源:互联网 发布:酷睿彩票源码2016 编辑:程序博客网 时间:2024/04/27 17:22
二分查找:
--先确定待查记录所在的范围,然后逐步缩小范围,直到找到或确认找不到该记录为止。

--前提:必须在具有顺序存储结构的有序表中进行。

--特点:比顺序查找方法效率高。最坏的情况下,需要比较Log2n次。

#include <iostream>using namespace std;int search(char* cs, int from, int to, char c){if(from > to) return -1;int m = (from+to)/2;if(cs[m] == c) return m;if(c > c[m])return search(cs, m+1, to, c);return search(cs, 0, m-1, c);}int search(char* cs, int n, char c){return search(cs, 0, n-1, c);}int main(){char cs[] = {'a','b','c','d','e','f','g'};int pos = search(cs, 7, 'e'};if(pos==-1) cout << "not found" << endl;else cout << "e pos:" << pos << endl;}


原创粉丝点击