The binary lookup algorithm is
OrderlyA more frequent algorithm used in arrays, the most common way to do this is to traverse an array, compare each element with a time complexity of O (n), but the binary lookup algorithm is better because its lookup time complexity is O (log2 N), such as the array { 0,1,2,3,4,5,6,7,8 9}, looking for element 6, executed with the binary lookup algorithm, in the order of:
1. The first step is to find the intermediate element, that is, 4, because 4<6, 6 must be in the array element after 4, then in {5,6,7,8,9} to find,
2. To find the median of {5,6,7,8,9}, 7,7>6, 6 should be in the array element to the left of 7, then only {5,6} is left, so you can find it by analogy.
The binary search algorithm is to continuously divide the array into half, and compare the intermediate elements with goal each time. The code is shown below, or it can be implemented with recursive algorithms, but it is generally not recommended to take into account the low efficiency of recursive algorithms.
#include <iostream>
int search (int *scr,unsigned int len,int goal);
int main ()
{
int num;
int tab[10]={0,1,2,3,4,5,6,7,8,9};
int location;
std::cout<< "Please input the number want to search:";
std::cin>>num;
Location=search (tab,10,num);
if (location!=-1)
std::cout<< "The number ' s location is" <<location+1<<std::endl;
else
std::cout<< "The number don ' t exist" <<std::endl;
return 0;
}
int search (int *scr,unsigned int len,int goal)
{
unsigned int low = 0;
unsigned int high = len-1;
while (Low<=high)
{
unsigned int mid = low + (high-low);//Prevent overflow
if (scr[mid]==goal)
return mid;
else if (scr[mid]<goal) Low
= mid +1;
else high
= mid-1;
}
return-1;
}
Here's a pretty good tip: don't use mid = (low + high)/2,
Instead of using mid=low+ ((high-low)/2), the reason is
There is an integer overflow problem with (Low+high)/2. The problem occurs when the result of Low+high is greater than the maximum value that can be represented by the expression result type, so that when the overflow is generated, then/2 does not produce the correct result