Monday 10 March 2014

Program In C++ to find time complexity of binary search

#include<iostream.h>
#include<conio.h>
#include<time.h>
#include<dos.h>
int main()
{  clock_t start,end;
start=clock();
clrscr();
int a[10],n,beg,last,mid,ele,flag=-1;
cout<<"Enter size of array: (SORTED)";
cin>>n;
cout<<"\nEnter Array: ";
for(int i=0;i<n;i++)
{ cin>>a[i];
}
cout<<"\nEnter The Element To Be Searched: ";
cin>>ele;
beg=0;last=n;
while(beg!=last)
{ mid=(beg+last)/2;
if(a[mid]==ele)
{ cout<<"Element Found At Position: "<<mid+1;
flag=0;
break;}
else if(a[mid]<ele)
{ beg=mid-1; }
else
last=mid+1;
}
if(flag==-1)
cout<<"Element Not Found In The Array !!!!";
delay(2000);
end=clock();
cout<<"\nTime Taken Is: "<<(end-start)/CLK_TCK;
getch();
return 0;

}

No comments:

Post a Comment