C + + binary method for finding keywords in arrays _c language

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.