C++ Code With Examples Job Interviews

Binary Search in C++ with Code Example

What is Binary Search 

Binary search is an effective algorithm for finding a item from a sorted list of things. It works by over and again dividing in half the portion of the list that could contain the item, until you’ve limited the potential areas to only one

Binary Search in c++ Code example

using namespace std;

int main()
int count, i, arr[30], num, first, last, middle;
cout<<“Enter the Element You Want?:”;

for (i=0; i<count; i++)
cout<<“Enter Your Number “<<(i+1)<<“: “;
cout<<“Enter the number that you are going to search:”;
first = 0;
last = count-1;
middle = (first+last)/2;
while (first <= last)
if(arr[middle] < num)
first = middle + 1;

else if(arr[middle] == num)
cout<<num<<” found in the array at the location “<<middle+1<<“\n”;
else {
last = middle – 1;
middle = (first + last)/2;
if(first > last)
cout<<num<<” not found in the array”;
return 0;

Out Put Screen 

Leave a Comment