The example in this article describes a method for finding keywords in an array using C + + binary. Share to everyone for your reference. as follows:
* This program demonstrates the implementation of the two-point lookup algorithm (for arrays from small to large).
* * #include <iostream> using namespace std; /* Function: Implement the binary lookup of arrays (only the algorithm is suitable for arrays from small to large) to return the value: the subscript of the keyword in the array, return-1 indicates that a[was not found]: array to search for Len: array elements key: keyword to find/int bin
Search (int a[], int len, int key) {int i = LEN/2;
int II = 0;
if (Len < 1) return-1; if ((Key > A[i]) && (len-i > 0)) {II = Binsearch (a+i+1, Len-i-1, key);//Find if (ii!= in the second half of the array) -1 Return II + i + 1;
Plus the length of the first half of the array else return-1;
else if (Key < a[i] && i > 0)//Find return Binsearch (A, I, key) in the first half segment array; else if (key = = A[i]) return i; Returns the return-1 of the keyword in the array else.
keyword} int main () {int a[] = {2, 4, 5, 20, 24, 35, 66, 78, 98} not found in array
int len = sizeof (a)/sizeof (int);
int I, key =-1;
while (1) {cin>>key;
i = Binsearch (A, Len, key);
printf ("%d\n", I);
if (key >) break;
return 0; }
I hope this article will help you with your C + + programming.