C++ binary method of finding keywords in an array

  • 2020-05-05 11:33:27
  • OfStack

This article illustrates the C++ binary method for finding keywords in an array. Share with you for your reference. The details are as follows:


/*
   This program demonstrates the binary search algorithm ( For arrays arranged from smallest to largest ) The implementation of the. 
*/
#include <iostream>
using namespace std;
/*
   Function:   Implement binary search of array ( The algorithm only works for arrays arranged from smallest to largest )
   Return value: the index of the keyword in the array ,  return -1 Means not found 
  a[]:   The array to search 
  len:   Number of array elements 
  key:   The keyword to look for 
*/
int binSearch(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); //  Look in the second half of the array 
    if(ii != -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) //  Look in the first half of the array 
    return binSearch(a, i, key);
  else if(key == a[i])
    return i; //  Returns the index of a keyword in an array 
  else
    return -1; //  The keyword was not found in the array 
}
int main()
{
  int a[] = {2, 4, 5, 20, 24, 35, 66, 78, 98};
  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 > 100)
      break;
  }
  return 0;
}

I hope this article is helpful for your C++ programming.


Related articles: