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

The output should be:

Enter the total number of elements: 5
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

LEAVE A REPLY

Please enter your comment!
Please enter your name here