# Binary Search in C++

For the binary search program in C++, if the array values are not defined already then it will ask the user first to enter the size of the array. Then the user will enter array elements one by one. After adding all the elements to array ask the user to enter the element to search in an array by using the binary search.

In binary search all the array elements must be sorted already, otherwise, we will need to sort them first. If the duplicate numbers are entered by the user then there is no guarantee which element will be found in the binary search.

The program first checks whether the element is present at middle if not then the element will be compared with middle value if results greater then it is present in left sub-array otherwise present in right sub-array.

## Program Example

### Implementing the binary search in C++:

Following is the C++ program in which binary search is implemented

#include <iostream> using namespace std; int main() { int count, j, elements[50], search_num, first, last, mid; cout<<"Enter the total number of elements :"; cin>>count; cout<<"\nEnter ">>count>>" numbers:\n"; for (j=0; j<count; j++) { cin>>elements[j]; } cout<<"\nWhich number that you want to search: "; cin>>search_num; first = 0; last = count-1; mid = (first+last)/2; // binary search while (first <= last) { if(elements[mid] < search_num){ first = mid + 1; } else if(elements[mid] == search_num){ cout<<search_num<<" found in array at "<<mid+1<<"\n"; break; } else { last = mid - 1; } mid = (first + last)/2; } if(first > last){ cout<<search_num<<" Not found in an array"; } return 0; }

The output should be:

Enter 5 numbers:

44

76

55

63

1

Which number that you want to search: 45

45 Not found in an array

55 found in the array at 3

### LATEST POSTS

- Binary Search in Java
- How to Print Without Newline in Python
- numpy.dot() in Python
- numpy.ones() in Python
- Read and Write text to files in Python
- Binary Search in C
- C++ do-while loop with Example
- fscanf() in C with Examples
- Python square root sqrt() method
- PHP implode() function
- How to Sort Pandas DataFrame with Examples
- C++ abs() Absolute Value with Examples