codescracker


c++

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 */
	
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int n, i, arr[50], search, first, last, middle;
	cout<<"Enter total number of elements :";
	cin>>n;
	cout<<"Enter "<<n<<" number :";
	for (i=0; i<n; i++)
	{
		cin>>arr[i];
	}
	cout<<"Enter a number to find :";
	cin>>search;
	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";
			break;
		}
		else
		{
			 last = middle - 1;
		}
		middle = (first + last)/2;
	}
	if(first > last)
	{
		cout<<"Not found! "<<search<<" is not present in the list.";
	}
	getch();
}

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 »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test