c# 搜索 二进制
Here you will learn about binary search in C++.
在这里,您将了解C ++中的二进制搜索。
Binary search is an algorithm used to search for an element in a sorted array. In this algorithm the targeted element is compared with middle element. If both elements are equal then position of middle element is returned and hence targeted element is found.
二进制搜索是一种用于在排序数组中搜索元素的算法。 在该算法中,将目标元素与中间元素进行比较。 如果两个元素相等,则返回中间元素的位置,从而找到目标元素。
If both elements are unequal then if targeted element is less or more than middle element we discard the lower or upper half and the search continues by finding new middle element.
如果两个元素都不相等,则如果目标元素小于或大于中间元素,我们将丢弃下半部分或上半部分,并通过查找新的中间元素来继续搜索。
Also Read: Linear Search in C++
另请阅读: C ++中的线性搜索
Below program shows how to implement binary search algorithm in C++.
下面的程序显示了如何在C ++中实现二进制搜索算法。
C ++二进制搜索程序 (Program for Binary Search in C++)
#include<iostream>
using namespace std;
int main()
{
int search(int [],int,int);
int n,i,a[100],e,res;
cout<<"How Many Elements:";
cin>>n;
cout<<"\nEnter Elements of Array in Ascending order\n";
for(i=0;i<n;++i)
{
cin>>a[i];
}
cout<<"\nEnter element to search:";
cin>>e;
res=search(a,n,e);
if(res!=-1)
cout<<"\nElement found at position "<<res+1;
else
cout<<"\nElement is not found....!!!";
return 0;
}
int search(int a[],int n,int e)
{
int f,l,m;
f=0;
l=n-1;
while(f<=l)
{
m=(f+l)/2;
if(e==a[m])
return(m);
else
if(e>a[m])
f=m+1;
else
l=m-1;
}
return -1;
}
Output
输出量
How Many Elements:5
多少元素:5
Enter Elements of Array in Ascending order 12 39 40 68 77
以升序输入数组元素 12 39 40 68 77
Enter element to search:40
输入要搜索的元素:40
Element found at position 3
在位置3找到元素
Comment below if you have any doubts related to above program for binary search in C++.
如果您对上面的C ++二进制搜索程序有任何疑问,请在下面评论。
翻译自: https://www.thecrazyprogrammer.com/2011/08/c-program-to-explain-binary-search-in.html
c# 搜索 二进制