Program to implement Binary Search Algorithm

#include <iostream.h>
template<class T>
int binarySearch(T a[], int n, T& x)
	int left = 0;                       // left end of segment
	int right = n - 1;                  // right end of segment
	while (left <= right)
		int middle = (left + right)/2;   // middle of segment
		if (x == a[middle]) return middle;
		if (x > a[middle]) left = middle + 1;
		else right = middle - 1;
	return -1; // x not found
int main()
	int a[10],n,t;
	cout<<"Enter the size:";
	cout<<"enter the elements in sorted order:";
	for(int i=0;i<n;i++)
	cout<<"enter the element to search:";
	int f=binarySearch(a,n,t);
		cout<<"element not found";
		cout<<"element found at index:"<<f;
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

4 thoughts on “Program to implement Binary Search Algorithm

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.