给定一个数组,我们必须使用binary_search()搜索元素,此函数是C ++标准模板库的算法标头的功能。
它是一个内置函数,用于使用二进制搜索算法从数组中搜索元素。
语法:
binary_search(start_address, end_address, element_to_search);
这里,
start_address-开始数组元素的指针
end_address-结束数组元素的指针
element_to_search-要搜索的元素
步骤:
声明并定义一个数组
对数组进行排序(这里,我们使用sort()函数按升序对数组进行排序)。
使用binary_search()函数查找元素。
打印带有其索引的消息(如果存在)。
#include <iostream>
#include <algorithm>
using namespace std;
//显示数组列表的功能
void dispArray(int arr[], int size)
{
for(int i = 0; i < size; i++)
cout <<" "<< arr[i];
cout<<endl;
}
//二进制搜索的主要代码
int main(){
int a[]= {10, 1, 20, 2, 30, 4};
//获取数组长度
int arr_length = sizeof(a) / sizeof(int);
//打印数组
cout<<"Array elements are: ";
dispArray(a, arr_length);
//对数组排序
sort(a, a + arr_length);
cout<<"Sorted array elements: ";
dispArray(a, arr_length);
//在数组中搜索30-
if(binary_search(a, a+ arr_length, 30))
cout<<"Element found"<<endl;
else
cout<<"Element does not found"<<endl;
return 0;
}输出结果
Array elements are: 10 1 20 2 30 4 Sorted array elements: 1 2 4 10 20 30 Element found