二分查找:
--先确定待查记录所在的范围,然后逐步缩小范围,直到找到或确认找不到该记录为止。
--前提:必须在具有顺序存储结构的有序表中进行。
--先确定待查记录所在的范围,然后逐步缩小范围,直到找到或确认找不到该记录为止。
--前提:必须在具有顺序存储结构的有序表中进行。
--特点:比顺序查找方法效率高。最坏的情况下,需要比较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;
}