C++ implementation of binary search algorithm

  • 2020-06-12 10:01:28
  • OfStack

Two points to find

The 2-point search algorithm, in other words, gives a value key in an ordered array, and then compares it with the middle of the array first. If key is greater than the middle value, the next comparison after mid is performed until the equivalent value is found, and its position can be obtained.

[

Premise: The records in the linear table must be keyword ordered (usually from small to large), and the linear table must be stored sequentially.
Basic idea: take the intermediate record as the comparison object. If the given value is equal to the key of the intermediate record, the search is successful. If the given value is less than the key of the intermediate record, the search will continue in the left half of the intermediate record. Otherwise, look in the right half. Repeat until the lookup succeeds or fails.

]

#include<iostream>
#include<stdio.h> 
#define N 10
using namespace std;
int main()
{
int a[N],front,end,mid,i,x;
cout<<" Please enter the sorted sequence 10 A: "<<endl;
for(i=0;i<N;i++)
{
cin>>a[i];
}
cout<<" Please enter the number you want to query x"<<endl;
cin>>x;
front=0;
end=N-1;
mid=(front+end)/2;
while(front<end&&a[mid]!=x)
{
if(a[mid]>x) end=mid-1;
if(a[mid]<x) front=mid+1;
mid=(front+end)/2;
 }
 if(a[mid]!=x)
 {
 printf(" The number could not be found! ");
}
else
{
printf(" Yes, the number is at number one %d location ",mid+1);
 } 
return 0;
}

Postscript:

[

Search and sort are algorithms that are often used in the program design. The search is relatively simple and consists of no more than sequential search, 2-minute search, hash table search and 2-cross sort tree search.
During the interview, whether it's a loop or a recursion, the interviewer expects the candidate to come up with a complete 2-point lookup code, or he might not be interested in continuing the interview.

]

conclusion


Related articles: