Declaration: images and content based on www.bilibili.com/video/av813…

Principle:

The core code

#include<iostream> #include<algorithm> using namespace std; void binarySearch(int a[],int target,int length); int main(){ int a[10]; Cout <<" Please enter 10 elements of array "<<endl; for(int i=0; i <10; i++){ cin>>a[i]; } int target; int length=sizeof(a)/sizeof(a[0]); Cout <<" Please enter the element you are looking for "<<endl; cin>>target; binarySearch(a,target,length); return 0; } void binarySearch(int a[],int target,int length){ int begin=0; int end=length-1; int mid; sort(a,a+length); while(begin<=end){ mid=(begin+end)/2; if(a[mid]==target) break; if(a[mid]<target) begin=mid+1; if(a[mid]>target) end=mid-1; } if(begin>end){cout<<" no "<<endl; Found,} else {cout < < "" < < target < <" is the subscript for "< < mid < <" elements "< < endl; }}Copy the code