Program to implement Binary Search Algorithm

by Nideesh C on April 12, 2011 · 0 comments

in C++




#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:";
	cin>>n;
	cout<<"enter the elements in sorted order:";
	for(int i=0;i<n;i++)
		cin>>a[i];
	cout<<"enter the element to search:";
	cin>>t;
	int f=binarySearch(a,n,t);
	if(f==-1)
		cout<<"element not found";
	else
		cout<<"element found at index:"<<f;
}



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C++ program to implement Binary Search Tree(BST) and its Operations
  2. C program to accept N numbers sorted in ascending order and to search for a given number using binary search. Report success or failure in the form of suitable messages
  3. C++ program to implement Heap sort Algorithm
  4. C++ program to implement Quick sort Algorithm using class
  5. C program to input N numbers (integers or reals) and store them in an array. Conduct a linear search for a given key number and report success or failure in the form of a suitable message

Leave a Comment

Previous post:

Next post: