C ++ STL中的二进制搜索功能
二进制搜索是一种搜索算法,用于查找目标值在排序数组中的位置。二进制搜索将目标值与已排序数组的中间元素进行比较。二进制搜索的时间复杂度为O(1)。这是一个我们实现各种C++程序。C++STL中的二进制搜索功能
算法
Begin
Initialize the vector of integer values.
The functions are used here:
binary_search(start_pointer, end_pointer, value) = Returns true if the value present in array otherwise false.
lower_bound(start_pointer, end_pointer, value) = Returns pointer to “position of value” if container
contains 1 occurrence of value. Returns pointer to “first position of value” if container contains
multiple occurrence of value. Returns pointer to “position of next higher number than value” if container does not contain occurrence of value.
upper_bound(start_pointer, end_pointer, value) = Returns pointer to “position of next higher valuethan
value” if container contains 1 occurrence of value. Returns pointer to “first position of next higher
number than last occurrence of value” if container contains multiple occurrence of value. Returns
pointer to “position of next higher number than value” if container does not contain occurrence of value.
Print the results.
End.范例程式码
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> a = {6,7,10,14,16,20};
if (binary_search(a.begin(), a.end(), 50))
cout << "50 exists in vector";
else
cout << "50 does not exist";
cout << endl;
if (binary_search(a.begin(), a.end(), 7))
cout << "7 exists in the vector";
else
cout << "7 does not exist";
cout << endl;
cout << "The position of 7 using lower_bound ";
cout << lower_bound(a.begin(), a.end(), 7) - a.begin();
cout << endl;
cout << "The position of 7 using upper_bound ";
cout << upper_bound(a.begin(), a.end(), 7) - a.begin();
cout << endl;
}输出结果
50 does not exist 7 exists in the vector The position of 7 using lower_bound 1 The position of 7 using upper_bound 2
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿