binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.
Binary search runs in at worst logarithmic time, making comparisons, where is the number of elements in the array and is the binary logarithm and using only constant space. Although specialized data structures designed for fast searching—such as hash tables—can be searched more efficiently, binary search applies to a wider range of search problems.
Although the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation.
//implementation and time analysis of binary searching....
#include<iostream>
#include<sys/time.h>
using namespace std;
struct timeval t1,t2;
void bin_srch(int n,int x[],int find)
{
int beg,end,mid;
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end && x[mid]!=find)
{
if(x[mid]<find)
beg=mid+1;
else
end=mid-1;
mid=(beg+end)/2;
}
if(x[mid]==find)
{
cout<<"\nData is Found at Location : "<<mid;
}
else
{
cout<<"Data is Not Found";
}
}
int main()
{
int a[100],n,i,srch;
double t;
cout<<"\n------------ BINARY SEARCH ------------ \n\n";
cout<<"Enter No. of Elements= ";
cin>>n;
cout<<"\nEnter Elements ::-\n";
for(i=1;i<=n;i++)
{
cin>>a[i];
}
gettimeofday(&t1,'\0');
for(i=1;i<=n-1;i++)
{
for(int j=n;j>=i+1;j--)
{
int temp;
if(a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
cout<<"Sorted Element is:";
for(i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
cout<<"\n\nEnter Item you want to Search ::- ";
cin>>srch;
bin_srch(n,a,srch);
gettimeofday(&t2,'\0');
t=(double)(t2.tv_usec-t1.tv_usec)/1000000+(double)(t2.tv_usec-t1.tv_usec);
cout<<"\n\n Time required for binary searching is :"<<t<<" usec."<<endl;
return 0;
}
/*******************************************************************************
OUTPUT
------------ BINARY SEARCH ------------
Enter No. of Elements= 7
Enter Elements ::-
6
30
78
99
121
35
1
Sorted Element is:1 6 30 35 78 99 121
Enter Item you want to Search ::- 78
Data is Found at Location : 5
Time required for binary searching is :550540 usec.
***************************************************************************/
EmoticonEmoticon