二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
//vs2017
#include<iostream>
using namespace std;
#include<algorithm>
int binarySearch(int a[], int n, int target)
{
int i = 0, j = n-1, mid = 0;
while (i <= j)
{
mid = (i + j) / 2;
if (a[mid] == target) return mid;
else if (a[mid] > target) j = mid-1;
else if(a[mid] < target)
i = mid + 1;
}
return -1;
}
int main()
{
int a[105] = {1,2,3,4,5};
int target ;
while (cin >> target) {
int n = 5;
cout << binarySearch(a, n, target)<<endl;
}
return 0;
}
法二:
如果是字符串
直接用find()函数
string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string s;
cin >> s;
cout << s.find('5');
return 0;
}