Binary Search in C++

Binary search is nothing but a searching algorithm to find an element and its location in an array. The only condition for binary searching is the array must be sorted in ascending order.

The whole array is divided into two halves. When user enter an element it compares with the middle element. If the input element is greater then the second halves of the array is considered.

If the entered element is lesser than the middle element then the first half of the array is considered. This is continued till the element is obtained.

Binary Search in C++

binarysearch() is a function which is used to find the element and its position in an array. The array must be sorted in ascending order. We can use if, else condition along with binarysearch() function.

Binary Search in C++

#include
using namespace std;
int binarySearch(int arr[], int p, int r, int num) {
   if (p <= r) {
      int mid = (p + r)/2;
      if (arr[mid] == num)
         return mid ;
      if (arr[mid] > num)
         return binarySearch(arr, p, mid-1, num);
      if (arr[mid] < num)
         return binarySearch(arr, mid+1, r, num);
   }
   return -1;
}
int main(void) {
   int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
   int n = sizeof(arr)/ sizeof(arr[0]);
   int num;
   cout << "Enter the number to search: \n";
   cin >> num;
   int index = binarySearch (arr, 0, n-1, num);
   if(index == -1){
      cout<< num <<" is not present in the array";
   }else{
      cout<< num <<" is present at index "<< index <<" in the array";
   }
   return 0;
}
Read Also : Diamond Pattern in C++

Output

Enter the number to search
20
20 is present at index 5 in the array

Final Words

I hope this article helps you to Binary Search in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment