Binary Search
Binary Search
Live Demo
#include<iostream>
if (p <= r) {
if (arr[mid] == num)
return mid ;
return -1;
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
if(index == -1)
else
Output
33 is present at index 7 in the array
Binary Search is a method to find the required element in a sorted array by repeatedly halving the
array and searching in the half.
This method is done by starting with the whole array. Then it is halved. If the required data value is
greater than the element at the middle of the array, then the upper half of the array is considered.
Otherwise, the lower half is considered. This is done continuously until either the required data value
is obtained or the remaining array is empty.
A program that demonstrates binary search in C++ is given below.
Example
Live Demo
#include<iostream>
if (p <= r) {
if (arr[mid] == num)
return mid ;
return -1;
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
if(index == -1)
else
cout<< num <<" is present at index "<< index <<" in the array";
return 0;
Output
33 is present at index 7 in the array
In the above program, binarySearch() is a recursive function that is used to find the required element
in the array using binary search. The function takes the array, its lower bound and upper bound as
well as the number to be found as parameters. This is shown below.
Then the midpoint of the array is calculated. If the value at the midpoint is equal to num, then it is
returned. If the value is greater than num, then array calls itself recursively with the lower bound p
and upper bound mid-1. If the value is less than num, then array calls itself recursively with the lower
bound mid+1 and upper bound r. This can be seen by the following code snippet.
if (p <= r) {
if (arr[mid] == num)
return mid ;
return -1;
In the main() function, the array arr[] is defined. The size of the array is calculated and the number to
be found is specified. Then binarySearch() is called to find the index of the number. If the value
returned by binarySearch() is -1, then the number is not in the array. Otherwise the index value is
returned. This is given below.
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
if(index == -1)
else
cout<< num <<" is present at index "<< index <<" in the array";
return 0;