二分查找

来源:互联网 发布:宝贝标题优化技巧 编辑:程序博客网 时间:2024/06/06 01:19

二分查找:

1.      算法描述:如果序列A已排好序,就可以将该序列的中点与v进行比较。根据比较的结果,原序列中就有一半可以不用再做进一步的考虑了。

2.      算法的代码实现:

#include<iostream>

#include<vector>

usingnamespace std;

//a升序排列

intBINARY_FIND(vector<int>a, int key)

{

unsigned Left_pos = 0;

unsigned Right_pos = a.size() - 1;

unsigned k = (Left_pos + Right_pos)/2;

while((key != a[k]) && (k >0)&& (k < a.size()))

{

           if(key > a[k])

                    Left_pos = k + 1;

           else

                    Right_pos = k - 1;

           k = (Left_pos + Right_pos)/2;

}

if(key == a[k])

           return k;

else

           return -1;

}

 

intmain()

{

int a[] = {1, 3, 5, 7, 8, 9,45};

vector<int>b(a, a+7);

int c = BINARY_FIND(b, 0);

if(c != -1)

           cout << b[c] << " isin the: " << c+1 << endl;

else

           cout << "the key is notexit" << endl;

return 0;

}

3.算法运行时间的增长率:lgn

0 0