C++ Program Binary Search

« Previous Program Next Program »

Binary Search in C++

To perform binary search or to search an element using binary search in C++ Programming, you have to ask to the user to enter the array size then ask to enter the array elements.

Now ask to enter an element that is going to be search to start searching that element using binary search technique and display the position of the element on the screen if found as shown here in the following program.

C++ Programming Code for Binary Search

Following C++ program first ask to the user to enter "how many element he/she want to store in array", then ask to enter the array elements. After storing the element in the array, program ask to the user to enter the element which he/she want to search in the array whether that number is present or not.

The searching technique used here is binary search which is fast technique :

/* C++ Program - Binary Search */
void main()
	int n, i, arr[50], search, first, last, middle;
	cout<<"Enter total number of elements :";
	cout<<"Enter "<<n<<" number :";
	for (i=0; i<n; i++)
	cout<<"Enter a number to find :";
	first = 0;
	last = n-1;
	middle = (first+last)/2;
	while (first <= last)
		if(arr[middle] < search)
			first = middle + 1;

		else if(arr[middle] == search)
			cout<<search<<" found at location "<<middle+1<<"\n";
			 last = middle - 1;
		middle = (first + last)/2;
	if(first > last)
		cout<<"Not found! "<<search<<" is not present in the list.";

When the above C++ program is compile and executed, it will produce the following result. Above C++ Programming Example Output (Element found):

binary search c++ programming

Above C++ Programming Example Output (Element Not found):

c++ binary search program

Same Program in Other Language

You may like the same program in other programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test