您的位置:首页 > 编程语言 > C语言/C++

二分法查找C++实现

2016-09-27 15:28 274 查看
#include <iostream>
#include <vector>
using namespace std;

int binary_seacher(vector<int> &v, int target)
{
if (v.empty())
return -1;

int index1 = 0, index2 = v.size() - 1, mid = 0;

while (index1 <= index2)
{
mid = (index1 + index2) / 2;
if (v[mid] == target)
return mid;

if (v[mid] > target)
index2 = mid-1;
if (v[mid] < target)
index1 = mid+1;
}

return -1;
}

int main()
{
int n = 0, target = 0;

cin >> n >> target;
vector<int> v(n);

for (int i = 0; i < n; i++)
{
cin >> v[i];
}

cout << binary_seacher(v, target);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分法查找