In: Computer Science
Write a program in C++ to implement Binary Search Algorithm. Assume the data given in an array. Use number of data N at least more than 10. The function Binary Search should return the index of the search key V.
ANSWER: Here I am giving you the code and output please like it.
CODE:
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int ele)
{
   while (l <= r) {
       int m = l + (r - l) / 2;
       // Checking if ele is present at
middle
       if (arr[m] == ele)
           return m;
       // If ele greater, ignoring left
half
       if (arr[m] < ele)
           l = m + 1;
       // If ele is smaller then
ignoring right half
       else
           r = m - 1;
   }
   return -1;
}
int main(void)
{
       int N;
cout<<"Enter the size of the array: ";
   cin>>N;
   int arr[N];
   cout<<"Enter "<<N<<" elements in the
array: \n";
   for(int i=0;i<N;i++){
       cin>>arr[i];
   }
     
   int x;
   cout<<"\nEnter your number to search in the
array:";
   cin>>x;
     
  
   int result = binarySearch(arr, 0, N - 1, x);
   (result == -1) ? cout << "Element is not present
in array"
          
    : cout << "Element is present at index "
<< result;
   return 0;
}
OUTPUT:
