At the end of February, the end of the spring to the warm, bright days, huifeng genial, sometimes really want to take the kite before, rushed out to experience a field run of joy. But also just think about it, more and more house I always can not leave the hands of the notebook computer.
Also do not know is the cause of the temperature rise or chunkun suddenly top of the reason, looked at a few days of the binary search algorithm only to understand it.
The binary lookup algorithm is a more efficient and concise algorithm than a sequential lookup, with a lookup length of up to ㏒2n+1 (the depth of the decision tree), and an average lookup length of ㏒2 (n+1)-1, but it has a big drawback that it is necessary to require the lookup sequence to store ordered tables sequentially.
Each of these algorithms can be represented by iteration and recursion, and I will use the C + + to represent the following.
Iterative form of C + +:
#include <stdio.h>
int find (int a[],int x,int low,int High)
{
int mid;
if (low>high) //if ... . else .... Error!!!
return-1;
while (Low<=high)
{
mid= (Low+high)/2;
if (a[mid]==x)
return mid;
else if (a[mid]>x) high
= Mid-1;
else if (a[mid]<x) Low
= mid + 1;
}
}
int main ()
{
int a[20]={2,3,6,7,12,18,19,21,25,28,30,33,37,39,42,45,47,49,50,51};
int x,i;
printf ("Existing number is: \ n");
for (i=0;i<20;i++)
printf ("%d", A[i]);
printf ("\ n Please enter the number to look for:");
scanf ("%d", &x);
if ((I=find (a,x,0,19)) >=0)
printf ("%d is the number of%d \ n", x,i+1);
else
printf ("%d\n not Found", x);
return 0;
}
In the IF program, why should I add an inexplicable comment--if...else ... error. Because I wanted to use this structure before, but later found that I made a low-level error, our goal is to continue to cycle in the sub-program to change the upper and lower limits, to divide and conquer the algorithm, and if ... else ... It's just a judgment run, of course, not the same as our requirements.
A/C + + recursive form:
#include <stdio.h>
int find (int a[],int x,int low,int high)
{int mid;
if (Low>high)
return-1;
Mid= (Low+high)/2;
return mid;
if (a[mid]>x)
return find (a,x,low,mid-1);
return find (A,x,mid+1,high);
}
int main ()
{
int a[20]={2,3,6,7,12,18,19,21,25,28,30,33,37,39,42,45,47,49,50,51};
int x,i;
printf ("Existing number is: \ n");
for (i=0;i<20;i++)
printf ("%d", A[i]);
printf ("\ n Please enter the number to look for:");
scanf ("%d", &x);
if ((I=find (a,x,0,19)) >=0)
printf ("%d is the number of%d \ n", x,i+1);
else
printf ("%d\n not Found", x);
return 0;
}
The great recursive algorithm, but we have changed the data is easily thrown to the program itself, although to consume memory stack space, but the algorithm is relatively simple.