C++

C++ Binary Search Program – Detailed Instructions From [A-Z]

This C++ software uses the binary search method to find the entered number in the list of numbers and returns the number’s position if it is.

An instance is the C++ binary search program.

A sorted array is searched by a binary search algorithm for the target value.

An array must be sorted in either ascending or descending order before performing a binary search.

  • Step 1, split the list of components in half.
  • Step 2: In the second step, the target value is compared to the array’s middle element. If the middle element is matched, the search stops here and doesn’t move on.
  • Step 3: If not, we start our search in the lower half of the array if the element is less than the middle element.
  • Step 4: If not, we start the search in the upper half of the array if the element is larger than the middle element.
  • Step 5: Until our target element is located, we will go through steps 3, 4, and 5 once more.
#include <iostream>
using namespace std;

int binarySearch(int[], int, int, int);

int main()
{
   int num[10] = {10, 22, 37, 55, 92, 118};
   int search_num, loc=-1;

   cout<<"Enter the number that you want to search: ";
   cin>>search_num;

   loc = binarySearch(num, 0, 6, search_num);

   if(loc != -1)
   {
      cout<<search_num<<" found in the array at the location: "<<loc;
   }
   else
   {
      cout<<"Element not found";
   }
   return 0;
}

int binarySearch(int a[], int first, int last, int search_num)
{
   int middle;
   if(last >= first)
   {
      middle = (first + last)/2;
      //Checking if the element is present at middle loc
      if(a[middle] == search_num)
      {
         return middle+1;
      }

      //Checking if the search element is present in greater half
      else if(a[middle] < search_num)
      {
         return binarySearch(a,middle+1,last,search_num);
      }

      //Checking if the search element is present in lower half
      else
      {
         return binarySearch(a,first,middle-1,search_num);
      }

   }
   return -1;
}

Output:

Enter the number that you want to search: 55
55 found in the array at the location: 4

C++ Program for Binary Search

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button